13

Is it possible to "wait" for multiple events before executing a function? I know its possible with jQuery deferred obejcts to use $.when to wait for two promises to resolve but I wondered if its possible with just plain old events?

Lets say a click event and a custom event trigger an alert, for example:

$.when("click", "customEvent").then(function(){ alert("yay"); });
Jon Wells
  • 4,191
  • 9
  • 40
  • 69

2 Answers2

29

You could use deferred, you just have to create them yourself.

var clickDfd = $.Deferred();
var eventDfd = $.Deferred();
$("div").on("click", function(e) {
   clickDfd.resolve();
});

$("div").on("some-event", function(e) {
   eventDfd.resolve();
});

$.when(clickDfd, eventDfd).done(function(){ 
    alert("yay"); 
});
Paul Hoenecke
  • 5,060
  • 1
  • 20
  • 20
1
var click = 0;
var hover = 0;
$("div").on("click mouseenter", function(e) {
   if(e.type == 'click') {
      click = 1;
      bana();
   }
   else if(e.type == 'mouseenter') {
      hover = 1;
      bana();
   }
});
function bana() {
   if(click == 1 && hover == 1) {
       alert(1);
       click = 0;
       hover = 0;
   }
   else {
       return false;
   }
}

Well, Checking event types and setting them in old way. Plain jQuery and JS.

Will alert 1 only when both events are done / fired.

Fiddle

Muhammad Talha Akbar
  • 9,952
  • 6
  • 38
  • 62
  • I've considered using this approach (and probably will), I was just curious if their was some sort of neat tidy "magic" jQuery way. Thanks for your answer :) – Jon Wells Feb 15 '13 at 10:29
  • @CrimsonChin we just don't sit back to wait for someone to do magic for you. You should search around web or try yourself. Well, in my point of view, I don't think tidy solution always help. You also need dirty solutions if you are well determined to make something big. – Muhammad Talha Akbar Feb 15 '13 at 10:34