DEV Community

Ali Shata
Ali Shata

Posted on

Unconventional Toggling Functionality in JS

Image description

As we all know that JavaScript has a toggle function to toggle a class status but from a functional point of view this is really doesn't perform well in many cases so and after some stackoverflowing I created this perfect and unconventional Toggling Way to toggle the status of a button between on and off (in case of a dark mode app such as this dark mode app) and I alse implemented it in a Stopwatch App

  • We define a Let variable call it whatever you like e.g. click_count and assign its value to 1
let click_count = 1
Enter fullscreen mode Exit fullscreen mode
  • Select the element you want to apply the toggling function for it e.g. button element and add a click event listener to it
document.querySelector("button").addEventListener("click", e => {

})
Enter fullscreen mode Exit fullscreen mode
  • Third, Increment the click_count variable
click_count++
Enter fullscreen mode Exit fullscreen mode
  • Add a condition to check for the Parity of click_count variable
if(click_count % 2 == 0){

}else{

}
Enter fullscreen mode Exit fullscreen mode
  • Consider the first condition as a mode 1 and the second condition (which is else) as mode 2

This is the actual modes for the dark mode I built

if(click_count % 2 == 0){
e.target.textContent = "On";              e.target.parentElement.parentElement.classList.add("dark")
 }
else{
    e.target.textContent = "Off"
    e.target.parentElement.parentElement.classList.remove("dark")
  }
})
Enter fullscreen mode Exit fullscreen mode

Finally I wish this could helped you in your projects or work



For more Info Follow me in:

Twitter: alishata128
Facebook: alishata122
Linkedin: alishata

Top comments (0)