javascript - EventListener for a class? -


i have eventlistener references id , works well, problem have @ least dozen places eventlistener needs reference dont want have dozen scripts same have different id. therea way have eventlistener references class use in places need it. thanks

javascript:

document.getelementbyid("chartjump").addeventlistener("click", function (e) { e.preventdefault() }); 

html:

<ul class="dropdown-menu" role="menu" aria-labelledby="dropdownmenugraphone">     <!--dropdown menu-->     <li role="presentation"><a role="menuitem" tabindex="-1" id="chartjumpone" href="#graphonechart">chart</a></li>     <li role="presentation"><a role="menuitem" tabindex="-1" id="tablejumpone" href="#graphonedata">data</a></li> </ul> 

yes, using classes. every element should have common class. , jquery can way:

$(document).ready(function () {   $(".classname").click(function (e) {     e.preventdefault();   }); }); 

get more info $.click() , $.ready(). have added , have given jquery solution.

using vanilla javascript, can achieve same functionality in 2 ways:

for old browsers:

window.onload = function () {   list = document.getelementsbyclassname("classname");   (var = 0; < list.length; i++) {     list[i].addeventlistener("click", function (e) {         e.preventdefault();     });   } }; 

for new browsers:

window.onload = function () {   list = document.queryselectorall(".classname");   (var = 0; < list.length; i++) {     list[i].addeventlistener("click", function (e) {         e.preventdefault();     });   } }; 

Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -

jdbc - Not able to establish database connection in eclipse -