0

When any element with .mytrigger is clicked, .myactive will be toggled on element with #mytarget.

I have the following code:

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

I need to have multiple triggers and from that this became confusing so I am unable to figure out the correct code. I can't use jquery for this.

3 Answers 3

1

Make as many as elements you want with class ".mytrigger" Just put onclick function as mentioned.

I hope this helps:- If not then please clarify your problem

HTML CODE

<a onclick="myFunction()" class="mytrigger">Button</a>
<div id="mytarget"><p>Hello</p></div>
<a onclick="myFunction()" class="mytrigger">Button</a>

Javascript CODE

function myFunction() {
  var element = document.getElementById("mytarget");
  element.classList.toggle("myactive");
}
Sign up to request clarification or add additional context in comments.

Comments

0

Using your code, I just changed document.getElementsById to document.getElementById (removing the s).

var navclick = document.getElementsByClassName("mytrigger");

for (var i = 0; i < navclick.length; i++) {
  navclick[i].onclick = function() {
      document.getElementById("mytarget").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>

Comments

0

Using addEventListener: It sets up a function that will be called whenever the specified event is delivered to the target.

document.getElementsByClassName('mytrigger').addEventListener('click', function() {
  document.getElementById('mytarget').classList.toggle("myactive");
});

Using document.bind:

document.bind('click', '.mytrigger', function(){  
 document.getElementById('mytarget').classList.toggle("myactive");
});

2 Comments

getElementsById?
@bewww, if it solves your problem, do accept the answer :) Accept an answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.