Search code examples
ecmascript-6ecmascript-5

How to toggle 2 classes with ECMAScript


I have two CSS classes. One that fades in an element's opacity class-A (using CSS3 Keyframes). And the other that fades out the opacity back to 0 class-B (using CSS3 Keyframes). Is there a way in pure ecmascript to toggle between these two classes? On first click, class-A loads. If you click it again, Class-B loads. If you click it a third time class-A loads, etc...

The following is the extent of my knowledge on toggling classes, relating to click event handling....

 var anchors = document.querySelectorAll('a');
 for (var i = 0, len = anchors.length; i < len; i++) {
    anchors[i].addEventListener('click', function (e) {
      e.preventDefault();
      if (this.classList.contains('my-trigger')) {
         document.querySelector('.what-i-am-fading-in-and-fading-out-on-clicks').classList.toggle('class-A');
      }
    }
 };

It's easy to fade in an element when I click on my link my-trigger the first time. But my end goal is to have a nice fade out process on the element, when my link is clicked a 2nd time, or 4th time, etc...How can I capitalize on this?


Solution

  • I dont know if i understand it right, but you could add an if statement to look if the opacity is 0 or 1, and then add the classes, once a class is added you dont need to look for it.

    You can change the opacity of #test to 1 or 0 and it will change respectivley to it.

    let test = document.getElementById("test");
    let but = document.getElementById("but");
    
    but.onclick = ()=>{
        if(test.classList.contains("a")||test.classList.contains("b")){
            test.classList.toggle("a");
            test.classList.toggle("b"); 
        }else{
            
            if(window.getComputedStyle(test).getPropertyValue("opacity") == "0"){
              test.classList.add("b")
            }else{
              test.classList.add("a")
            }
            
        }
    
    }
    #test{
        width:100px;
        height:25px;
        background:black;
        opacity:1;
    }
    
    #but{
        width:50px;
        background: lightgrey;
        margin-top:20px;
    }
    
    .a{
        opacity:0 !important;
        transition:opacity 300ms;
    }
    
    .b{
        opacity:1 !important;
        transition:opacity 300ms;
    }
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Grocery Bud</title>
        <!-- font-awesome -->
        <link
          rel="stylesheet"
          href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css"
        />
        <!-- styles -->
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div id="test"></div>
        <div id="but">Button</div>
    </body>
    <script src="app.js"></script>
    </html>