by Stian

Redirect page with jQuery / JavaScript

There are several different ways to do a clean redirect from one URL to another with some simple jQuery / javascript. I’ll start out here showing what in my opinion is the best way to simulate a HTTP redirect and then show a few other options that you have.

Pure javascript
// similar behavior as an HTTP redirect
window.location.replace("http://blog.degree.no");

This method is in my opinion the best, because the window.location.replace() is redirecting the page without putting the original page in the browser history.

// similar behavior as clicking on a link
window.location.href = "http://blog.degree.no";

This method works fine as well, but it will throw the user in to a back button loop if they would want to go back in history.

jQuery

My impression is that developers sometimes search for the “jQuery way” to do things and maybe you found this blog post searching for “redirect page with jQuery”? While there is a way to do this in jQuery, there is really no reason why you would want to do this as it could not be easier to with normal javascript. But since you searched for it, here it is.

$(location).attr("href",http://blog.degree.no);

 

image

  • Newbie

    Beautifull!! Thanks a lot for this information. Using plain javascript should do the trick here. Nice touch adding the comparison between href and replace as well :)