tzortzik
tzortzik

Reputation: 5133

events execution order

What is the execution order of two or more change events in jQuery?

$('#el').change(fn1);
$('#el').change(fn2);
$('#el').change(fn3);

I want to be sure that when I change the value of el, the change events will be executed in the exact order: fn1, fn2, fn3.

Upvotes: 2

Views: 53

Answers (1)

mohamedrias
mohamedrias

Reputation: 18576

The callback functions will execute in the order they are registered:

  <input type="text" id="element">

In JS:

$(function() {
  $("#element").change(function() {
    console.log("first"+this.value);
  });
   $("#element").change(function() {
    console.log("second"+this.value);
  });
   $("#element").change(function() {
    console.log("third"+this.value);
  });
});

As the value changes:

"first1"
"second1"
"third1"

DEMO

Even better solution would be:

function fn1() {
 // do something
}
function fn2() {
 // do something
}
function fn3() {
 // do something
}

Inside your event handler:

$("#el").change(function() {
   $.when(fn1).then(fn2).then(fn3).done(function(){
     // all done
   });
});

Upvotes: 1

Related Questions