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
Javascript execution is line by line. So whatever comes up, will be executed first. So adding the click code before the other method will work. Plus if there is any async call, then take a flag which is set only when you get response.
Every time you click on your button, you would see a message in your console saying clicked . The debounce method here takes in two arguments, callback & wait . callback is the function you want to execute, while wait is the configurable time period delay after which you want your callback to be executed.
If you want native JS to trigger click event without clicking then use the element id and click() method of JavaScript.
An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.
(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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With