Search code examples
javascriptclasstoggle

Javascript Toggle a class on clicked class element


Bit of a basic one, I was unable to to find exactly what I was after on Stack/Google..

Using vanilla javascript, I'm looking to simply toggle a class on the below .barBtn elements, specifically the one I click.

Sample JS Fiddle: https://jsfiddle.net/t376kL4q/

<div class="container">
    <div class="btnBar">
        <div class="barBtn">Wishlist</div>
        <div class="barBtn">Collection</div>
        <div class="barBtn">Info</div>
    </div>
</div>

<div class="container">
    <div class="btnBar">
        <div class="barBtn">Wishlist</div>
        <div class="barBtn">Collection</div>
        <div class="barBtn">Info</div>
    </div>
</div>

I have tried adapting others' code found on Stack/Google, e.g. this one which I've JSFiddle'd: https://jsfiddle.net/5rmqucj3/

Where I changed

document.getElementById("mytarget").

to

document.GetElementsByClassName("mytrigger").

(or even 'querySelector')... but I'm not sure how to correctly target the specific class element I click.


Whether or not the above (2nd link) is the best way to go about the JS of this I'm not sure, but generally just after a clean/simple way of achieving this.

Any help would be much appreciated.

Thanks


Solution

  • You need this

    var navclick = document.getElementsByClassName("mytrigger");
    for (var i = 0; i < navclick.length; i++) {
      navclick[i].onclick = function(e) {
        this.classList.toggle('myactive');
      }
    }
    .myactive {
      background-color: blue;
      color: white;
    }
    <button class="mytrigger">Button
        </button>
    
    <div id="mytarget">
      <p>Hello</p>
    </div>
    
    <button class="mytrigger">Button
        </button>