I made JS code to add a class into a mainDiv when I press on button. When I press again the class should be removed. However, what happens is when I press the first time the class is added, but when I press again the class is not removed.
"use strict";
const mainDiv = document.getElementById("main");
const myButton = document.querySelector("button");
if (myButton.textContent === "Add Class") {
myButton.onclick = function() {
mainDiv.classList.add("added-from-js");
this.textContent = "Remove Class";
};
} else if (myButton.textContent === "Remove Class") {
myButton.onclick = function() {
mainDiv.classList.remove("added-from-js");
this.textContent = "Add Class";
};
} else {
console.log("there is a problem in your code");
}
<div id="main" class="show cool main-div zero">Our Main Div</div>
<button>Add Class</button>
I tried to make toggle for class, without toggle method, to apply if condition and change the value of button each click
4
Answers
I think the problem in your code is with the conditional statement. The second condition is never true because the button text content is not yet "Remove Class". Therefore, when you click the button again, the first condition is still true, and the onclick event listener to add the class is executed again, but this time the button text content is already "Remove Class" because you changed it in the previous click.
You could add the event listener for both cases inside one conditional statement, and use a boolean flag to keep track of the class state. Something like this:
As @CBroe pointed out in their comment, your conditions only run once so your event handlers aren’t actually firing except when the script is first loaded and the conditions run.
Instead, you can use one handler and define your conditions inside like so:
your mistake using if statement
first you want to add the event onclick then inside the event you do your conditions
The problem here is that your code only runs once, and attach the handler to add the classs
"added-from-js"
and change the text to"Remove Class"
.If you want to actively listen to click events the best approach is to add an event listener. After each click your listener will check for the condition and proceed acordingly: