skip to Main Content

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


  1. 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:

    "use strict";
    const mainDiv = document.getElementById("main");
    const myButton = document.querySelector("button");
    let isClassAdded = false;
    
    myButton.onclick = function() {
      if (isClassAdded) {
        mainDiv.classList.remove("added-from-js");
        this.textContent = "Add Class";
        isClassAdded = false;
      } else {
        mainDiv.classList.add("added-from-js");
        this.textContent = "Remove Class";
        isClassAdded = true;
      }
    };
    
    Login or Signup to reply.
  2. 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:

    "use strict";
    const mainDiv = document.getElementById("main");
    const myButton = document.querySelector("button");
    
    myButton.onclick = function() {
      if (myButton.textContent === "Add Class") {
        console.log("change 1");
        mainDiv.classList.add("added-from-js");
        this.textContent = "Remove Class";
      } else if (myButton.textContent === "Remove Class") {
        console.log("change 2");
        mainDiv.classList.remove("added-from-js");
        this.textContent = "Add Class";
      } else {
        console.log("there is a problem in your code");
      }
    }
    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>JS training</title>
    </head>
    
    <body>
      <div id="main" class="show cool main-div zero">Our Main Div</div>
      <button>Add Class</button>
    </body>
    
    </html>
    Login or Signup to reply.
  3. <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>JS training</title>
    <link rel="stylesheet" href="style.css" />
    <script>
    
      function myfunc(myButton){
    
    if (myButton.innerText == "Add Class") {
        myButton.innerText = "Remove Class";
        document.getElementById("main").addClass("added-from-js");
    } else if (myButton.innerText == "Remove Class") {
    myButton.innerText = "Add Class";
    document.getElementById("main").removeClass("added-from-js");
    
    } else {
      console.log("there is a problem in your code");
    }
      }
    
      </script>
    </head>
    
    <body>
      <div id="main" class="show cool main-div zero">Our Main Div</div>
      <button onclick="myfunc(this)">Add Class</button>
      <script src="main.js"></script>
    </body>
    
    </html>
    

    your mistake using if statement
    first you want to add the event onclick then inside the event you do your conditions

    Login or Signup to reply.
  4. 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:

    myButton.addEventListener('click', function() {
      if (myButton.textContent === "Add Class") {
        mainDiv.classList.add("added-from-js");
        this.textContent = "Remove Class";
      } else if (myButton.textContent === "Remove Class") {
        mainDiv.classList.remove("added-from-js");
        this.textContent = "Add Class";
      } else {
        console.log("there is a problem in your code");
      }
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search