Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Triggering .click() events, one after the other

Tags:

jquery

I have a situation where I have to do multiple actions on a page in order to initialize it's settings. I do not have any code yet for it because, frankly I am having trouble finding a place to start on it.

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 accomplished?

like image 844
Joe Hoskinson Avatar asked Jan 26 '12 22:01

Joe Hoskinson


1 Answers

inside your first handler you could use a deferred object, resolve it in the ajax success callback and return a promise so you would chain your code like this (I haven't 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 a chainable utility object that can register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.

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

like image 182
Fabrizio Calderan Avatar answered Sep 21 '22 11:09

Fabrizio Calderan