I have an EventListener that references an Id and it works well, the only problem is that i have at least a dozen places where this EventListener needs to reference so i don
If you're referring to jQuery library in your script, then why use raw JS code, which is so difficult to write.
First of all add a class name for all your elements, then use the same class selector for attaching a event listener like click
to it
HTML CODE:
<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownMenuGraphOne">
<!--DROPDOWN MENU-->
<li role="presentation"><a role="menuitem" tabindex="-1" class='jumpChart' href="#graphOneChart">Chart</a></li>
<li role="presentation"><a role="menuitem" tabindex="-1" class='jumpChart' href="#graphOneData">Data</a></li>
JS Code:
$('.jumpChart').on('click',function(){
//handle the event here
});
For more info refer to jQuery forum: http://api.jquery.com
If you're not using jQuery
you can use querySelectorAll:
var els = document.querySelectorAll(".chartJump");
for (var i = 0; i < els.length; i++) {
els[i].addEventListener("click", function (e) {
e.preventDefault()
eventHandler();
});
};
If you've jQuery
you can use on:
$(".chartJump").on('click', function () {
// Your code
});
Yes, using classes. Every element should have a common class. And with jQuery you can do this way:
$(document).ready(function () {
$(".className").click(function (e) {
e.preventDefault();
});
});
Get more info about $.click() and $.ready(). As you have added jquery, I have given the jQuery solution.
Using vanilla JavaScript, you can achieve the same functionality in two ways:
For old browsers:
window.onload = function () {
list = document.getElementsByClassName("className");
for (var i = 0; i < list.length; i++) {
list[i].addEventListener("click", function (e) {
e.preventDefault();
});
}
};
For new browsers:
window.onload = function () {
list = document.querySelectorAll(".className");
for (var i = 0; i < list.length; i++) {
list[i].addEventListener("click", function (e) {
e.preventDefault();
});
}
};
you can assign a class to each of these elements and use a for loop to iterate through and place a eventListener.
var elements = document.querySelectorAll('.className');
for (i = 0; i < elements.length; ++i) {
elements[i].addEventListener('click', function() {
// Do something amazing
});
}
via: http://pencilscoop.com/2014/06/using-eventlisteners-on-multiple-elements
or you could just add onclick to your elements individually
<a role="menuitem" tabindex="-1" href="#graphOneChart" onclick="function1()">Chart</a>