Function not toggling how do I fix this problem?

Viewed 123

When the element's first clicked on its color should turn red. That part works. When the element's clicked on a second time it's should turn black, it's initial default color, and so on and so forth. That's the part that doesn't work. Once the element turns red it stays in that "state".

function toggleClass() {
  var monday = document.getElementById("monday");
  monday.classList.add("redColor");
  monday.classList.remove("redColor");
  this.classList.toggle("redColor");
}
monday.addEventListener("click", toggleClass)
.greenColor {
  color: green;
}

.redColor {
  color: red;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">

  <head>
    <meta charset="utf-8">
    <title>Practise App</title>
    <link rel="stylesheet" href="index.css">
  </head>
  <body>
    <div id="monday" class="">Monday</div>
    <script src="index.js" type="text/javascript"></script>
  </body>
</html>

3 Answers

You just need the toggle, it will toggle the class for you - you don't need the add or remove: monday.classList.toggle("redColor");

for example:

function toggleClass() {
  var monday = document.getElementById("monday");
  monday.classList.toggle("redColor");
}

function toggleClass() {
  var monday = document.getElementById("monday");
  monday.classList.toggle("redColor");
}
monday.addEventListener("click", toggleClass)
.greenColor {
  color: green;
}

.redColor {
  color: red;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">

  <head>
    <meta charset="utf-8">
    <title>Practise App</title>
    <link rel="stylesheet" href="index.css">
  </head>
  <body>
    <div id="monday" class="">Monday</div>
    <script src="index.js" type="text/javascript"></script>
  </body>
</html>

DOMTokenList.toggle()

The toggle() method of the DOMTokenList interface removes a given token from the list and returns false. If token doesn't exist it's added and the function returns true.

You do not need to use add() and remove(), simply toggle() should do the trick.

Also, as this keyword refers to the currently clicked element, I think you do not need to get the element by id here:

function toggleClass() {
  this.classList.toggle("redColor");
}
monday.addEventListener("click", toggleClass)
.redColor {
  color: red;
}
.greenColor {
  color: green;
}
<div id="monday" class="">Monday</div>

You don't need this two instructions:

monday.classList.add("redColor");
monday.classList.remove("redColor");

Just the toggle is enough. Also if you already captured the div in the variable monday, you don't need the reference to this:

function toggleClass() {
  var monday = document.getElementById("monday");
  monday.classList.toggle("redColor");
}
monday.addEventListener("click", toggleClass)

this should do the trick.

Here's a pen to illustrate: https://codepen.io/ePresas/pen/BaQjVwG

Related