Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
93
rated 0 times [  99] [ 6]  / answers: 1 / hits: 83048  / 12 Years ago, fri, august 3, 2012, 12:00:00

I add a click event handler to an element



 $(.elem).click(function(){
$.post(page.php.function(){
//code1
})
})


And then I trigger a click event



$(.elem).click();
//code2


How can i make sure that code2 executes after code1 executes


More From » jquery

 Answers
16

(Ignoring WebWorkers) JavaScript runs on a single thread, so you can be sure that code2 will always execute after code1.



Unless your code1 does something asynchronous like an Ajax call or a setTimeout(), in which case the triggered click handler will complete, then code2 will execute, then (eventually) the callback from the Ajax call (or setTimeout(), or whatever) will run.



EDIT: For your updated question, code2 will always execute before code1, because as I said above an async Ajax callback will happen later (even if the Ajax response is very fast, it won't call the callback until the current JS finishes).




How i make sure that code2 executes after code1 executes




Using .click() with no params is a shortcut to .trigger(click), but if you actually call .trigger() explicitly you can provide additional parameters that will be passed to the handler, which lets you do this:



$(.elem).click(function(e, callback) {
$.post(page.php.function(){
//code1

if (typeof callback === function)
callback();
});
});

$(.elem).trigger(click, function() {
// code 2 here
});


That is, within the click handler test whether a function has been passed in the callback parameter and if so call it. This means when the event occurs naturally there will be no callback, but when you trigger it programmatically and pass a function then that function will be executed. (Note that the parameter you pass with .trigger() doesn't have to be a function, it can be any type of data and you can pass more than one parameter, but for this purpose we want a function. See the .trigger() doco for more info.)



Demo: http://jsfiddle.net/nnnnnn/ZbRJ7/1/


[#83881] Thursday, August 2, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dustin

Total Points: 599
Total Questions: 105
Total Answers: 106

Location: Belarus
Member since Tue, Mar 14, 2023
1 Year ago
dustin questions
;