Add An Onclick Listener With An Existing Function Using Javascript
I have an existing javascript function: function changeColor(ID){ try{ initialize(); } finally{ changeDesign(ID); } } I want to do something like
Solution 1:
Assigning an event handler via the DOM API does not modify the actual HTML (in fact, the HTML source that the browser receives is readonly).
You have to assign a function to .onclick
, not a string:
for(var x=0; x<2; x++){
document.getElementById(x).onclick = changeColor;
}
where changeColor
is defined as
function changeColor(){
var ID = this.id; // `this` refers to element the handler is bound totry{
initialize();
}
finally{
changeDesign(ID);
}
}
I recommend to read the excellent articles about event handling on quirksmode.org.
Post a Comment for "Add An Onclick Listener With An Existing Function Using Javascript"