Home  »  ArticlesGuidesHow ToProgrammingTechnology   »   How do I Redirect to Another Webpage in JavaScript or jQuery?

How do I Redirect to Another Webpage in JavaScript or jQuery?

It is not uncommon to find that in web development projects you can do certain things in more than one way. If you want to redirect one web page to another using JavaScript, you will realize there is more than one way to correctly do it depending on the scenario.

One of the major factors to determine which method to use depends on the sort of behavior that you are looking for.

There are three main ways to perform the redirect that you want albeit some of these are not true redirects.

1. The ideal method to use is the location replace method. This method simulates a redirect and replaces the current history of the page making it impossible to use the back button to reach the original page. You can use location replace like so:

window.location.replace("http://local.brightwhiz");

2. You can use the location assigned to load a page and keep the browser history allowing you to use the back button. You can use location assign like so:

window.location.assign("http://local.brightwhiz");

3. This final option using location href simulates clicking of a link and is not a true redirect although it can also simulate a redirect. This method also maintains the browser history allowing you to use the back button.

window.location.href="http://local.brightwhiz";

Bonus; Redirect Using jQuery

Obviously, if you have included jQuery on your project for other functionality, you have the option of using it to redirect to another web page. The following are examples of the methods you can use:

$(location).attr('href','http://local.brightwhiz');

$(window).attr('location','http://local.brightwhiz');

$(location).prop('href', 'http://local.brightwhiz');

There you have it. That should get you started. Meanwhile, you can check out the official ECMAScript reference online.

Found this article interesting? Follow Brightwhiz on Facebook, Twitter, and YouTube to read and watch more content we post.