Vanilla JavaScript version of jQuery .click

JavascriptJqueryFunctionEvent Handling

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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;
    };
}

Solution 2 - Javascript

element.addEventListener('click', function() { ... }, false);

You have to locate the elements and make a loop to hook up each one.

Solution 3 - Javascript

Try the following

var clickHandler = function() { 
  // Your click handler
};

var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
  var current = anchors[i];
  current.addEventListener('click', clickHandler, false);
}

Note: As Ӫ_._Ӫ pointed out this will not work on IE8 and lower as it doesn't support addEventListener.

On IE8 you could use the following to subscribe to onclick. It's not a perfect substitute as it requires everyone to be cooperative but it may be able to help you out

var subscribeToOnClick = function(element) {
  if (element.onclick === undefined) {
    element.onclick = clickHandler;
  } else {
    var saved = element.onclick;
    element.onclick = function() {
      saved.apply(this, arguments);
      clickHandler.apply(this, arguments);
    }
  }
}

for (var i = 0; i < anchors.length; i++) {
  var current = anchors[i];
  subscribeToOnClick(current);
}

Solution 4 - Javascript

document.getElementById('elementID').onclick = function(){
      //click me function!
}

Solution 5 - Javascript

Here you go:

[].forEach.call( document.querySelectorAll( 'a' ), function ( a ) {
    a.addEventListener( 'click', function () {
        // code here
    }, false );
});

Live demo: http://jsfiddle.net/8Lvzc/3/

(doesn't work in IE8)

Also, I recommend event delegation...

Solution 6 - Javascript

I just stumbled upon this old question.

For new browsers (find support here: https://caniuse.com/?search=querySelectorAll)

My solution would be:

function clickFunction(event) {
  // code here
}

for (let elm of document.querySelectorAll("a")) {
  elm.addEventListener('click', clickFunction);
}

This is optimized to not create a new function for each element. This will add an "click" eventListener to each element, so if you do this more than once, several eventListeners for each element will be called.

To replace/set the "click" eventListener use the following code:

for (let elm of document.querySelectorAll("a")) {
  elm.onclick = clickFunction;
}

Will work on IE9 and up.

Solution 7 - Javascript

This will assign an onclick function to every a element.

var links = document.getElementsByTagName("a");
var linkClick = function() {
  //code here
};

for(var i = 0; i < links.length; i++){
  links[i].onclick = linkClick;
}

You can see it in action here.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDuck in CustardView Question on Stackoverflow
Solution 1 - JavascriptKevin BowersoxView Answer on Stackoverflow
Solution 2 - JavascriptDiodeus - James MacFarlaneView Answer on Stackoverflow
Solution 3 - JavascriptJaredParView Answer on Stackoverflow
Solution 4 - JavascriptNaftaliView Answer on Stackoverflow
Solution 5 - JavascriptŠime VidasView Answer on Stackoverflow
Solution 6 - JavascriptThomas PsikView Answer on Stackoverflow
Solution 7 - JavascriptPeter OlsonView Answer on Stackoverflow