How to call an action after click() in Jquery?

JavascriptJquery

Javascript Problem Overview


I want to load an image and some other actions after I click a certain DOM element, but I want to load them AFTER the clicking action finished.

Here is a code example:

 $("#message_link").click(function(){
   if (some_conditions...){
       $("#header").append("<div><img alt=\"Loader\"src=\"/images/ajax-loader.gif\"  /></div>");
   }
 });

The problem is that the if condition executes before the click action have finished(Or at least that is my impression). I need that the If condition executes after the click action has finished. Can some one please tell me a solution?

Thanks :)

Javascript Solutions


Solution 1 - Javascript

setTimeout may help out here

$("#message_link").click(function(){
   setTimeout(function() {
       if (some_conditions...){
           $("#header").append("<div><img alt=\"Loader\"src=\"/images/ajax-loader.gif\"  /></div>");
       }
   }, 100);
});

That will cause the div to be appended ~100ms after the click event occurs, if some_conditions are met.

Solution 2 - Javascript

If I've understood your question correctly, then you are looking for the mouseup event, rather than the click event:

$("#message_link").mouseup(function() {
    //Do stuff here
});

The mouseup event fires when the mouse button is released, and does not take into account whether the mouse button was pressed on that element, whereas click takes into account both mousedown and mouseup.

However, click should work fine, because it won't actually fire until the mouse button is released.

Solution 3 - Javascript

you can write events on elements like chain,

$(element).on('click',function(){
   //action on click
}).on('mouseup',function(){
   //action on mouseup (just before click event)
});

i've used it for removing cart items. same object, doing some action, after another action

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrogeliogView Question on Stackoverflow
Solution 1 - JavascriptKevin DeckerView Answer on Stackoverflow
Solution 2 - JavascriptJames AllardiceView Answer on Stackoverflow
Solution 3 - JavascripthrnskyView Answer on Stackoverflow