Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vanilla JavaScript version of jQuery .click

So maybe I'm just not looking in the right places but I can't find a good explanation of how to do the equivalent of jQuery's

$('a').click(function(){     // code here }); 

in plain old JavaScript?

Basically I want to run a function every time an a tag is clicked but I don't have the ability to load jQuery into the page to do it in the way above so I need to know how to do it using plain JavaScript.

like image 824
Duck in Custard Avatar asked Sep 26 '11 14:09

Duck in Custard


People also ask

Is jQuery vanilla JavaScript?

Vanilla JS helped the developers in creating dynamic websites. Then came jQuery, a library of tools created by developers around the world, using Javascript. In simple words, jQuery is a lightweight and easy to use JavaScript library that helps in creating complex functionalities with few lines of coding.

Is vanilla JavaScript JavaScript?

"VanillaJS is a name to refer to using plain JavaScript without any additional libraries like jQuery back in the days. People use it as a joke to remind other developers that many things can be done nowadays without the need for additional JavaScript libraries."

What is equivalent to jQuery?

The equivalent to $() or jQuery() in JavaScript is querySelector() or querySelectorAll() , which, just like with jQuery, you can call with a CSS selector.

What is vanilla in vanilla JavaScript?

Vanilla JavaScript refers to using plain Javascript without any additional libraries or frameworks. The term became popular when Eric Wastl created the Vanilla JS site in 2012 as a joke. The site tries to bring attention to the fact that you can use just plain Javascript in many cases.


1 Answers

Working Example: http://jsfiddle.net/6ZNws/

Html

<a href="something">CLick Here</a> <a href="something">CLick Here</a> <a href="something">CLick Here</a> 

Javascript:

var anchors = document.getElementsByTagName('a'); for(var z = 0; z < anchors.length; z++) {     var elem = anchors[z];        elem.onclick = function() {         alert("hello");         return false;     }; } 
like image 57
Kevin Bowersox Avatar answered Oct 25 '22 22:10

Kevin Bowersox