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(){
document.getElementById('elementID').onclick = function(){
//click me function!
}
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.onclick = clickFunction;
}
This is optimized to not create a new function for each element.
Will work on IE9 and up.
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.
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);
}
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;
};
}
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...