Monday, February 16, 2009

How to dynamically change the onclick handler

More related to just web development in general, but sometimes you might need to change the onclick event handler of an element. This can be a little tricky, but I find the best way to do this is:


element.onclick = function() {this_is_my_function($param)}


The tricky part is that the value of the onclick is a reference to the function and not the function itself. So if you simply put:

element.onclick = this_is_my_function($param)


It would actually fail. You need to wrap this under another function, hence the original code where the function() calls the this_is_my_function().