JQuery: firing .click () events, one by one

I have a situation where I need to perform several actions on a page to initialize it. I donโ€™t have a code yet, because, to be honest, Iโ€™m having trouble finding a place to start.

Here is what I want to do:

jQuery(document).ready(function($) { $('#element-one').trigger('click'); // wait for the first trigger event to complete (it loads ajax content into a div tag) // then move on to this one... $('#element-two').trigger('click'); // then move on to this one... $('#element-three').trigger('click'); // then move on to this one... $('#element-four').trigger('click'); // then finally move on to the last one $('#element-five').trigger('click'); }); 

How is this achieved?

+6
source share
1 answer

inside your first handler, you can use a deferred object, allow it in the ajax callback, and return a promise so you can bind the code this way (I have not tested)

  $.when( $('#element-one').triggerHandler('click') /* asynchronous task */ ).done(function() { $('#element-two').triggerHandler('click') /* synchronous task */ ... $('#element-five').triggerHandler('click') /* synchronous task */ }) 

from http://api.jquery.com/category/deferred-object/

jQuery.Deferred (), introduced in version 1.5, is an object with the ability to combine objects that can register multiple callbacks in a callback queue, call callback queues, and relay the success or failure status of any synchronous or asynchronous function.

Note. I used triggerHandle() instead of trigger() : http://api.jquery.com/triggerHandler/ just to be agnostic on the elements to which you attached your handlers. Use trigger() if it suits your needs

+10
source

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


All Articles