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.
4
Answers
Here’s a slight adaptation of your code.
el
gets the target element, and is used to get thestatus
and also to give it thenewStatus
once you’re finished updating the new value.and
are both performing assignment of
status
to a truthy string value, meaning the conditions will always be true and each block is always executed in turn.This means
will always be executed just before the
<h1>
element is updated.You must use
==
or===
for comparing equality.Note that this could be controlled with a single boolean, instead of doing string comparisons.
bool = !bool
is a quick way to flip a boolean value from true to false, and vice versa.This can be reduced to:
Just for a good practice – you should use a
boolean
to toggle the statement, not set astring
and check if it is exactly thatstring
. Even tho this is also working, it’s not really good practice 🙂In my code snippet, the
element
and aboolean
gets declared globally and inside the switch function, theinnerHTML
of theelement
is getting set either to the one or the otherstring
, depending on theboolean
. After that, theboolean
is toggled.A single
=
means assignment, so when you write:You are actually setting
status
to the value of the string.Use
===
for strict equality check.Beyond that, see the comments below for additional things to change.