Sathish Jayaram Sathish Jayaram - 1 month ago 9x
jQuery Question

How to make a Javascript event handler to execute first?

I have a page which uses jQuery & parsley plugin for form validation and submission. Below is the event handler for the form,

$('#formid').parsley().on('form:submit', function(event) {
//handle form submit

I have another pure JavaScript listener function to be executed on submit of the form. Below is the code snippet,

//Some code to be executed after form submit

I have a requirement not to use jQuery for the above function.

Now the problem is, parsley is stopping flow of events down the line by using

Because of this, the second event handler is not getting executed. Is there a way I could make my pure javascript handler to execute first? I came across this jQuery solution to bindUp an event handler. But I need pure javascript solution. Any help is greatly appreciated.

Here is JSFiddle for my problem.


The only way is to ensure that the addEventListener handler is added before the jQuery handler. jQuery will use addEventListener to add its handler for the event (at which point it will use that single handler for all handlers for that event on that element), and since handlers added with addEventListener are processed in the order they were added, your non-jQuery handler will be executed first by the browser.


// The first addEventListener handler -- does get called
document.getElementById("the-button").addEventListener("click", function() {
  console.log("first addEventListener handler called");
}, false);

// The jQuery handler that stops immediate propagation
$("#the-button").on("click", function(e) {
  console.log("jQuery handler called");

// The second addEventListener handler -- doesn't get called
document.getElementById("the-button").addEventListener("click", function() {
  console.log("this message won't be output");
}, false);
<input type="button" id="the-button" value="Click Me">
<script src=""></script>