How can I redirect the user from one page to another using jQuery or pure JavaScript?

How to automatically redirect a Web Page to another URL using jQuery or pure JavaScript?

javascript jquery redirect 

Nov 17

3 Answers

Redirect a Webpage Using Pure JavaScript or Core Javascript.

 

There are a couple of ways to redirect to another webpage with JavaScript. The most popular ones are location.href and location.replace:

// Simulate a mouse click:
window.location.href = "https://www.hrefcode.com";

// Simulate an HTTP redirect:
window.location.replace("https://www.hrefcode.com");

The difference between href and replace is that replace() removes the URL of the current document from the document history, meaning that it is not possible to use the "back" button to navigate back to the original document.

answered Dec 21


One does not simply redirect using jQuery

jQuery is not necessary, and window.location.replace(...) will best simulate an HTTP redirect.

window.location.replace(...) is better than using window.location.href, because replace() does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.

If you want to simulate someone clicking on a link, use location.href

If you want to simulate an HTTP redirect, use location.replace

For example:

// similar behavior as an HTTP redirect
window.location.replace("https://www.hrefcode.com");

// similar behavior as clicking on a link
window.location.href = "https://www.hrefcode.com";

answered Dec 21


5 ways to redirect a web page using JavaScript and jQuery

The redirection can also be divided into two categories, client-side and server-side. On the client-side, the redirection client is responsible for routing requests to another URL but in server-side redirection, it's the server's job to redirect to a new page.

1. Redirection using window.location.href of Javascript

window.location.href="http://newURL.com";

You should remember that window.location.href loads page from browser's cache and does not always send the request to the server.

2. Redirection using replace() function

window.location.replace("url"); 

Use the replace() method if you want to want to redirect to a new page and don't allow the user to navigate to the original page using the back button.

3. Redirection using window assign() function

window.location.assign("url"); 

Use the assign() method for redirection if you want to allow the user to use the back button to go back to the original document.

4. Redirection using navigate function

window.navigate("page.html");

This code is similar to the first method and the page will be loaded from the cache if available instead of sending a new request to the server.

5. Redirect web page using jQuery

var url = "http://google.com";
$(location).attr('href',url);

answered Dec 21


Login and Submit Your Answer
Browse other questions tagged  javascript  jquery  redirect or ask your own question.