How do you force your Javascript event to run first, regardless of the order in which the events were added?

We solved this by just adding a little jQuery extension that inserts events at the head of the event chain:

$.fn.bindFirst = function(name, fn) {
  var elem, handlers, i, _len;
  this.bind(name, fn);
  for (i = 0, _len = this.length; i < _len; i++) {
    elem = this[i];
    handlers = jQuery._data(elem).events[name.split('.')[0]];

Then, to bind your event:

$(".foo").bindFirst("click", function() { /* Your handler */ });

Easy peasy!

Leave a Comment