How can I wait for a click event to complete
You can try writing this way:
$(".elem").live("click", function(){
//code1
})
// for newer jquery version from 1.9
$(".elem").on("click", function(){
//code1
})
And, your trigger will always execute as fired.
(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/
Wrap code2
in method and add it as a callback inside code1
so it will always get called after code1
executes
code2 = function(){/*code2*/};
$(".elem").click(function(){
//code1
code2();
})