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

Share this post: