10

How to call a function once after change() event complete?

for example, something like this: ( I know jQuery Doesn't have callback method as default )

$('#element').change( function(){
                     // do something on change
                     // $('#milestonesSelect').multiselect({ minWidth: 120 , height : '200px' ,selectedList: 4  }).multiselectfilter();
                      // some animation calls ...
                      // ...
                     }, function(){
                     // do something after complete
                      alert('another codes has completed when i called');
                     }
                   );

Is it possible to call a single callback after all the codes on change method done, except call a complete callback for every functions on it?

I need to do something after the change event has completed

Shall I need to set order to methods in change handler?

Alireza
  • 1,428
  • 4
  • 21
  • 33

3 Answers3

11

You can probably make use of event bubbling and register a callback in the document.

$(document).on('change', '#element', function(){
    console.log('after all callbacks')
});

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • 3
    And what if your events are already triggered in this way? ie. `jQuery('#myelement').on('change', 'select,input', function(){ ... do stuff });` How would you attach a callback after these changes are triggered? – pspahn Mar 30 '15 at 20:57
  • 1
    event bubbling link is not working in your answer. Please update for later use. – vivek Nov 03 '17 at 09:05
2

I just spent some time exploring this myself, and decided to submit my answer to this question as well. This is not utilizing any of jQuery's deferred methods, which might be a better approach. I haven't explored them enough to have an opinion on the matter.

$("#element").change(function() {
  handler().after(callBack($("#element").val()));
}

function handler() {
  alert("Event handler");
}

function callBack(foo) {
  alert(foo);
}

Demo: JSFiddle

David Kartik
  • 454
  • 4
  • 9
0

If I understand your question correctly, this will execute code only one time after a change event is fired:

var changed = false;

$('#element').on('change', function() {
    if ( !changed ) {
        // do something on change
        changed = true;
    }
  }
});
chrx
  • 3,524
  • 1
  • 15
  • 17
  • as you said `this will execute code only one time after a change event is fired` but I need to do something after event completed not fired. I don't want to do it at the same time with another executions – Alireza Apr 04 '13 at 07:52