I’m still learning html and Javascript, so I’m not too good at it. I’m trying to make it so that when I press a button, some text switches from "On" to "Off" and vise versa.
function switch_status() {
//Setting status to opposite
if (status = "Turn Appearance Off:") {
status = "Turn Appearance On:"
};
if (status = "Turn Appearance On:") {
status = "Turn Appearance Off:"
};
//Printing it out
status_print.innerHTML = status;
}
var status = "Turn Appearance Off:";
var status_print = document.getElementById("status_print");
//calling function
switch_status();
<h1 id="status_print">Turn Appearance On:</h1>
<button type="button" onclick="switch_status()">Click Me!</button>
As you can see, it’s supposed to switch from On to Off when I hit the button. But it doesn’t seem to work, help would much be appreciated.
>Solution :
Here’s a slight adaptation of your code. el gets the target element, and is used to get the status and also to give it the newStatus once you’re finished updating the new value.
function switch_status() {
let el = document.querySelector('#status_print');
let status = el.innerHTML;
let newStatus;
//Setting status to opposite
if (status === "Turn Appearance Off:") {
newStatus = "Turn Appearance On:"
};
if (status === "Turn Appearance On:") {
newStatus = "Turn Appearance Off:"
};
//Printing it out
el.innerHTML = newStatus;
}
<h1 id="status_print">Turn Appearance On:</h1>
<button type="button" onclick="switch_status()">Click Me!</button>