This post will discuss how to redirect to another webpage in JavaScript and jQuery.

1. Redirecting to another webpage with JavaScript

There are several ways to redirect a page in JavaScript, all of which include the use of the window.location property, which returns a Location object, representing the location (URL) of the current document. To redirect to another webpage with JavaScript, we can use any of the following methods:

1. Using location.href

When we assign a URL to the window.location.href property, the associated document navigates to the new page from the same or different origin. Since window is a global object, window.location.href can be shortened to location.href. Also location is a synonym of location.href, we can directly assign a value to the location object.

2. Using location.assign() function

We can also navigate to a new URL using the location.assign() method. The assign() method loads a new web page by changing the location property. It takes a URL as an argument and replaces the current web page with the new one.

 
Note that the assign() method will save the current page in the session history, i.e., the user can go back using the back button. Also if the specified URL is of a different origin, it may fail due to CORS policy.

3. Using location.replace() function

There is another location object method called replace(), which replaces the current document with the document at the specified URL. Unlike the assign() method, this replaces the session History entry, and the user can’t navigate back to the originating page with the back button.

2. Redirecting to another webpage with jQuery

To redirect to another webpage with jQuery, we can assign a URL to href property of the location object using the .prop() or .attr() method. Here is the complete code for redirecting to another webpage with jQuery:

 
We can also directly assign a value to the location object.

That’s all about redirecting to another webpage in JavaScript and jQuery.