6

I am novice to jquery. Suppose i have a list of 10 "a" tags all attached to an event handler mouseover, click, mouseout respectively.
what i want to do is iterate over all the "a" elements and trigger these events using jquery trigger.
The issue i am facing is that, these events take sometime to get triggered, hence when i run the code, all i see the result change only on the last element. And not the intermediates.

$.each($("#styles a"), function(){
    console.log("picked up " + $(this));
    setTimeout(qwe($(this)), 2000);
});

function qwe(obj) {
    console.log(obj.attr("id"));
    $.when(obj.trigger("mouseover").trigger("click").trigger("mouseout"))
        .then(function () {
            console.log("Changing Result Value" + $("#textTag").text());
        });
}

Is there way to chain these events sequentially i.e.
Second Element's events should be trigged only when the trigger action of the first elements is complete. i tried searching over SO, but mostly articles revolve around triggering only single event. Thanks

Andbdrew
  • 11,788
  • 4
  • 33
  • 37
jaipster
  • 11,967
  • 2
  • 21
  • 24
  • I'm guessing jQuery's `.trigger()` doesn't return a promise, and even if it did, there's no way to know when the event handlers finish, as you could have put anything in there, and there is no callback ? – adeneo Jun 15 '13 at 14:07
  • i have not put any callbacks yet. on googling, found this kind of functionality is more close to running automated test cases. due to the constraint i will have to run via jquery. this will have to run on third party sites, so i cannot guarantee callbacks in the impl of the eventhandles – jaipster Jun 15 '13 at 14:14

1 Answers1

0

Create $.Deferred objects for each part of the chain, then bind them to be resolved when the events are actually triggered:

callbacks = [$.Deferred(), $.Deferred(), $.Deferred()];
obj.on('mouseover', callbacks[0].resolve);
obj.on('click', callbacks[1].resolve);
obj.on('mouseout', callbacks[2].resolve);
$.when(callbacks).done(function() { console.log('all three have fired'); });

You'd need additional logic to ensure that the order is preserved -- perhaps by using 'reject' if click isn't triggered before mouseout.

Luke
  • 919
  • 5
  • 8