JSFiddle - React, Tailwind, and code Playground
HTML
<div>
Click me and if you see, <b>3</b>, <b>1</b>, and then <b>2</b>, then the script is working.
</div>
CSS
body {
padding: 20px;
}
div {
cursor: pointer;
border: 1px solid #CCC;
background: #EEE;
padding: 1.25em;
font-family: Helvetica;
color: #555;
font-size: 1.25em;
}
JavaScript
// [name] is the name of the event "click", "mouseover", ..
// same as you'd pass it to bind()
// [fn] is the handler function
$.fn.bindFirst = function(name, fn) {
// bind as you normally would
// don't want to miss out on any jQuery magic
this.on(name, fn);
// Thanks to a comment by @Martin, adding support for
// namespaced events too.
this.each(function() {
var handlers = $._data(this, 'events')[name.split('.')[0]];
console.log(handlers);
// take out the handler we just inserted from the end
var handler = handlers.pop();
// move it at the beginning
handlers.splice(0, 0, handler);
});
};
$("div").click(function() { alert("1"); });
$("div").click(function() { alert("2"); });
$("div").bindFirst('click', function() { alert("3"); });