cross browser - Want to reverse the order of click events attached to one element in jquery -
i have 1 scenario want change order of click events attached 1 element. using jquery 1.3.2, used following code reverse order of events
$("#button").bind('click',first); var foo = $.data( $('#button').get(0), 'events' ).click; var firsthandler; $.each( foo, function(i,defination) { firsthandler = defination; $('#button').unbind('click', defination); }); $("#button").bind('click',second); $("#button").bind('click',firsthandler); function first() { alert("first"); }; function second() { alert("second"); };
this code works in other browsers(ff, ie, safari) not working expected in chrome. here online version of code please have working code @ online fiddle
can guide me ?
you can reverse clicks taking .clicks
array, copying before removing it, unbinding clicks, re-binding in reverse order, this:
var clicks = $('#button').data('events').click.slice(); var button = $('#button').unbind('click'); $.each(clicks.reverse(), function() { button.click(this); });
you can give try here. or, bit more generic, let's make plugin:
$.fn.reversehandlers = function(eventtype) { return this.each(function() { var handlers = $.data(this, 'events')[eventtype].slice(); var elem = $(this).unbind(eventtype); $.each(handlers.reverse(), function() { elem.bind(eventtype, this.handler); }); }); };
you can test format here, just call by: $("#button").reversehandlers("click");
note jquery 1.3.x users: event structure formatted differently prior 1.4+, if needs version works 1.3.x please comment here , i'll add it.
Comments
Post a Comment