Reputation: 39
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.
Upvotes: 0
Views: 5492
Reputation: 6541
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");
});
Upvotes: 0
Reputation: 181
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>
Upvotes: 0
Reputation: 357
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");
}
Upvotes: 1