Wednesday, April 11, 2012
Today I had to solve a task wich seemed to be quite easy... I had to copy a "click" event from an element. To copy an "onclick" attribute...it's a piece of cake. BUT, how do you copy a jQuery "click" event?
I found an interesting conversation about this problem here, but I couldn't find a solution for my problem:
I'm not 100% sure you understand my problem, so here are some example codes:
This is a common "a" tag with an onclick attribute:
This click event can be copied with this code:
BUT, what's the case with this method?
How do I copy this click event?
Well, I dove in jQuery-s source code because I knew it can be done. jQuery has a .clone() function which has an attribute to decide, whether to copy the events too or not. This is what I found:
The most interesting part is this:
The events are saved inside (jQuery._data( src )).events. To stay by my example, the solution will look like this:
This way I can make a copy of the function bound to the element. And of course, if there are more bindings to one element, they can be reached with "...click.handler", "...click.handler", etc.
I hope this little trick helped you too.