In this post we will learn how to change or add JavaScript function on the onclick event for the anchor tag. Infact, you can use this methodology add/change JavaScript function for almost any event and on elements which support such events.
In usual scenario one tends to change/add JavaScript function in the following way, which is not the correct way to do so,
//THIS WILL NOT WORK <script> function change_event() { document.getElementById('my_tag').onclick = "new_func();" } </script> <a href="#" id="my_tag" onclick="change_event();" >My test</a>
However, if we wrap the function in an anonymous function then we surely can achieve what we wanted to. Look at the following example.
//THIS WILL WORK <script> function change_event() { document.getElementById('my_tag').onclick = function(){new_func();} } </script> <a href="#" id="my_tag" onclick="change_event();" >My test</a>
Note, if you want to bind multiple JavaScript functions on a single event, then you need to define all function in one anonymous function. Failing to do so will make the last function override the ones defined above. For example the above change_event function can be rewritten as :
function change_event() { //note all three functions are defined together. document.getElementById('my_tag').onclick = function(){new_func();new_func2();new_func2();} }
This way you can also associate JavaScript function on the dynamically created DOM elements.
Hope this helps.
Stay Digified !!
Sachin Khosla



Why would you do that? Why not just use the javascript to specify the event and avoid using onClick?
`document.getElementById(‘my_tag’).onclick = function(){ … }`
And what if i want to specify a pre-defined function on different elements ? Write the function definition n-times ?
That is where getElementsByClassName ( http://robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/ ) and getElementsByTagName come in, you can then apply the functionality to all of the elements that match your requirements.
@SeanJA dude you did not get what I am saying.. Suppose the new_func() has a 50 line definition. So you want me to write :
document.getElementById(‘my_tag1′).onclick = function {50
lines of code}
document.getElementById(‘my_tag2′).onclick = function { another 50 lines of code}
document.getElementById(‘my_tag3′).onclick = function { another 50 lines of code}
I can have these 50 lines of code in one function called “new_func()” and bind it with different elements.
Think now its clear ?
No, that is not what I mean… I mean for you do use html properly and add an identifier to group those elements:
(don’t know if it will get mad at me for adding html…)
[ a class="my_class" ] my link [/a]
then:
var elements = getElementsByClassName(‘my_class’, ‘a’);
for(var i in elements){
(function(elem) {
elem.onclick = function(){
//50 lines of code
}
})(elements[i]); // immediately call the temp function with our element
}