JQuery Trigger Events programmatically and wait for the previous event to complete to trigger the next

I am new to jquery. Suppose I have a list of 10 "a" tags, all attached to the mouse pointer of an event handler, click accordingly. What I want to do is iterate over all the elements of "a" and trigger these events using jquery trigger.
The problem I am facing is that these events take time to run, so when I run the code, all I see is the change in the result only on the last element. And not intermediate.

$.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 a way to sequentially link these events, i.e. Events of the second element should be triggered only when the action of the trigger of the first elements is completed. I tried doing a search on SO, but mostly articles revolve around triggering only one event. Thanks

+6
source share
1 answer

Create $ .Deferred objects for each part of the chain, and then bind them to resolution when the events actually fire:

 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 will need additional logic to ensure that order is maintained - perhaps using "reject" if the click does not start before the mouse.

0
source

Source: https://habr.com/ru/post/947364/


All Articles