This is my code to dynamically set the onclick attribute to links, but without me clicking the links itself, the alert is triggered.
window.onload = function() {
var links = document.getElementsByTagName("a");
for(var i=0;i<links.length;i++) {
elm = links[i];
elm.setAttribute("onclick", alert("you clicked a lik"));
}
}
change the corresponding line to:
If you pass as argument a function call (such as
alert('msg')), the function is executed imediatley and the actual passed argument is the function’s return value. All you have to do is wrap your eventHandler code into an anonymous function.Also, you can declare a function that handles your event and send it’s name as argument :
P.S. : I recommend using the
addEventListenerfunctionality instead of plain old onEvent inline attributes :