Damon
Damon

Reputation: 10818

Does javascript still execute if I navigate to a different page?

Say I have a set-up like this:

$('#mylink').click(function(event){
   savePost();
});

<a id="mylink" href="http://google.com">my link</a>

If I click the link will I be gone to a different page without giving the function a chance to execute?

What if savePost() has ajax and a callback function? Will it execute regardless of what page the browser is on when the script executes? (or would I have to preventDefault on the link and put the window.location command within the callback)

Upvotes: 0

Views: 113

Answers (3)

ThiefMaster
ThiefMaster

Reputation: 318808

Call event.preventDefault(); to prevent the link from actually changing the page. Otherwise the page will change after the onclick function has been executed.

Upvotes: 1

Sergey Volosevich
Sergey Volosevich

Reputation: 377

Script will be executed first, then window.location

Upvotes: 2

Marek Sebera
Marek Sebera

Reputation: 40681

Yes,

onclick script will be executed before changing window.location

on ajax callback, i don't think so, as ajax and callback are asynchronous calls,
so if you need to navigate only after success perform of ajax call use complete(jqXHR, textStatus) callback on jQuery.ajax() together with preventDefault()

see http://api.jquery.com/jQuery.ajax/

Upvotes: 1

Related Questions