How to redirect the user from one page to another using jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the JavaScript window.location Property

You can simply use the JavaScript window.location property to make a page redirect, you don't need any jQuery for this. If you want to redirect the user from one page to another automatically, you can use the syntax window.location.replace("page_url"), the benefit here is, the replace() method does not save the originating page in the session history, meaning the user won't be able to use the browser back button to navigate to it, which prevents the user from getting redirected to the destination page once again.

Create a blank HTML file and put the following example code inside. Now open it in a web browser, you will be automatically redirected to the home page of this site after 10 seconds. If you notice carefully, you will find the browser back button is still disabled.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>JavaScript Automatic Page Redirect</title>
  • <script type="text/javascript">
  •     function pageRedirect() {
  •         window.location.replace("https://www.tutorialrepublic.com/");
  •     }      
  •     setTimeout("pageRedirect()", 10000);
  • </script>
  • </head>
  • <body>
  •     <p><strong>Note:</strong> You will be redirected to the tutorialrepublic.com in 10 sec. You are not able to get back to this page by clicking the browser back button.</p>
  • </body>
  • </html>

However, if you want to redirect the page when an event occurs, such as when the user click on a button, you can just use the window.location.href="page_url", which produce the similar effect when someone click a link to navigates to other page.

Similarly, create another HTML file and put the following example code inside. Now open it in a web browser and click the button on the page, it will redirect you to the home page of this site. Also, at this time you can see the browser back button becomes active.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>JavaScript Page Redirect onclick Event</title>
  • <script type="text/javascript">
  •     function pageRedirect() {
  •       window.location.href = "https://www.tutorialrepublic.com/";
  •     }      
  • </script> 
  • </head>
  • <body>
  •     <button type="button" onclick="pageRedirect()">Go to Tutorial Republic</button>
  •     <p><strong>Note:</strong> You can go to the tutorialrepublic.com by clicking the button above. You can get back to this page by clicking the browser back button.</p>
  • </body>
  • </html>

Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.