Saturday, November 30, 2013

Ordering HTML Element Events using jQuery

The first thing we need to do is get hold of the events object for a given DOM element. The problem is it's not a public piece of data as far as jQuery is concerned, so we have to use the undocumented _data function to get at it. (ref :http://blog.jquery.com/2011/11/08/building-a-slimmer-jquery/)


$("input.myEventFirst").click(function(event) {
    if ($(this).hasClass("disabled")) {
        event.stopImmediatePropagation();
        return false;
    }
});
$('.input').each(function(){
   if($(this).hasClass('myEventFirst')){
      var eventList = $._data($("#button")[0], "events");
      eventList.click.unshift(eventList.click.pop());
  }
});
We bind our new click event first, and that gets added as the last entry to the click property of the events object. The click property is an array, so we just pop it off the end and unshift it onto the front

There are lots of other uses and needs to insert something into the beginning of an event queue in jQuery, but if you've read this far then you already have that need so I won't bore you with them. :)