Home > database >  Javascript Toggle a class on clicked class element
Javascript Toggle a class on clicked class element

Time:04-11

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 >
    <div >
        <div >Wishlist</div>
        <div >Collection</div>
        <div >Info</div>
    </div>
</div>

<div >
    <div >
        <div >Wishlist</div>
        <div >Collection</div>
        <div >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

CodePudding user response:

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 >Button
    </button>

<div id="mytarget">
  <p>Hello</p>
</div>

<button >Button
    </button>

  • Related