Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute 2 JavaScript functions in order

I have a function with two lines and I want them to be executed in order. The function is :

showNotification(message){
    $("#notificationMessageBody").html(message); // line1
    $("#notificationModal").modal('show');       //line2
}

So, whenever I call showNotification("Hello World!") how do I ensure line1 is executed before line2 (meaning content loading is done before the modal triggers) Basically, I am trying to fill in my message in modal body and then show it, not before filling.

--EDIT--

The functions are indeed executing one after the other, but my modal pops before jQuery loads my message into my #notificationMessageBody

As a result, for example : If I call showNotification("Hello") I get a modal with "Hello" (the arrangement of modals and stuff is done), but then after that if I call showNotification("World") modal appears with "Hello" first then after that it changes to "World".

Note : "Hello" and "World" are big junk of text, so loading that into my DIV must be taking some time, I believe. Even though they are executed one after other, it appears (to common-er) that firstly modal is popping and then replacement is done. I hope the picture is a little clear now.

No AJAX involved anywhere here around the function. Basically, this is my custom alert() function one can say. A modal with proper ID is there in my page. I change the modal-body content(with jQuery's .html() function) and trigger the modal to show, as seen from the code.

like image 349
krozaine Avatar asked Oct 18 '22 18:10

krozaine


1 Answers

You can use the .promise() method (added in jQuery 1.6) to ensure the second one is executed after first is completed:

$("#notificationMessageBody").html(message).promise().done(function() {
    $("#notificationModal").modal('show');  
});
like image 129
Shadow Wizard Hates Omicron Avatar answered Oct 21 '22 16:10

Shadow Wizard Hates Omicron