Jquery Trigger Events programmatically and wait until the action of previous event is complete to fire next one
Asked Answered
B

1

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

Bowdlerize answered 15/6, 2013 at 14:4 Comment(2)
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 ?Probity
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 eventhandlesBowdlerize
S
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.

Sculptress answered 5/7, 2013 at 16:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.