Home » Redirect By JavaScript With Example

Redirect By JavaScript With Example

Last updated on June 16, 2021 by

In this tutorial, we will learn how to redirect by JavaScript with example. There are numerous ways to redirect a webpage to another page including server-side redirects, HTML meta refresh redirects, and JavaScript redirects. Let’s just dive into it.

Table of Contents
1. Redirect By JavaScript Methods
2. Example #1: Redirect On Button Click
3. Example #2: Time Delayed Redirect
4. Example #3: Redirect With Hash(#) URL
5. Example #4: Redirect On Page Load
6. Example #5: Browser Based Redirection
7. Example #6: JavaScript Redirect To URL With Parameters
8. Example #7: JavaScript Conditional Redirect

Redirect By JavaScript Methods

There are number of methods to redirect a web page via JavaScript using a number of methods. Let’s quickly list them and conclude with the recommended one.

In JavaScript, the window.location is used to get the Location object with information of the current web page (document) and also to modify it. Here is the list of possible ways to redirect a page to another page in JavaScript:

// This is used to redirect using the link click
window.location.href = "https://www.example.com";

// Assigns a new URL to the current window.
window.location.assign("https://www.example.com");

// This won't keep the history of previous page
window.location.replace("https://www.example.com");

Example #1: Redirect On Button Click

Just add the onclick event to the button:

<button onclick="location.href='https://www.example.com';" id="btnHome">Link Button</button>

If you don’t want to add it as an inline JavaScript then just use the JavaScript block as below with button ID:

<button id="btnHome">Link Button</button>

<script type="text/javascript">
    document.getElementById("btnHome").onclick = function () {
        location.href="https://www.yoursite.com";
    };
</script>

Example #2: Time Delayed Redirect

If you would like to redirect to another page after some time passes then try the following example:

<script type="text/javascript">
    setTimeout(function() {
        window.location.href = "https://www.example.com";
    }, 7000);
</script>

When the above code gets executed then the page will be redirected after 7 seconds once page fully loads. You can change 7000 (7 x 1000 in milliseconds) as you wish.

Example #3: Redirect With Hash(#) URL

Sometimes, you may want to redirect with hash URL then you can follow the below code:

<script type="text/javascript">
    var initialPage = location.pathname;
    location.replace('https:www.example.com/#' + initialPage);
</script>

Actually, location.pathname returns the path of the current URL. This will be helpful when you have an only a single endpoint in your URL but you can replace the initialPage variable to your hash URL endpoint. For example,

<script type="text/javascript">
    location.replace('https:www.example.com/#section1');
</script>

Example #4: Redirect On Page Load

Occasionally, you might want to redirect the page on page load then you can use the following code:

<script type="text/javascript">
    window.location.href = "https://www.example.com";
</script>

Use the above code within <head></head> HTML element. This will instantly redirect the page on page load.

Example #5: Browser Based Redirection

The following example shows how to redirect page to a different page based on their browsers.

<html>
   <head>     
      <script type="text/javascript">
            var browsername=navigator.appName;
            
            if( browsername == "Netscape" ) {
               window.location="http://www.example.com/ns.htm";
            } else if ( browsername =="Microsoft Internet Explorer") {
               window.location="http://www.example.com/ie.htm";
            } else {
               window.location="http://www.example.com/other.htm";
            }
      </script>      
   </head>
   
   <body>
   </body>
</html>

In the above example, we are fetching the browser name using the navigator.appName and based on the browser’s name we are redirecting to the appropriate page.

Example #6: JavaScript Redirect To URL With Parameters

Usually, we want to pass additional details with the URL which we have known as parameters or query strings. If you would like to pass some parameters with URL redirect in JavaScript then use the following code.

window.location.href = "registration.php?action=edit&username=" + encodeURIComponent( $("#txtUserName").val());

Example #7: JavaScript Conditional Redirect

Let’s say we would like to redirect a page when certain condition met. For example, if any element has particular class or not, if page has any particular URL or not, if particular HTML element has particular value or not, etc.

let pageVal = document.getElementById("page_url").value;
if ( pageVal === 'login' ) {
    window.location = "login.html";
} else {
    window.location = "logout.html";
}

In the above example, we are checking that an element with an ID page_url has a value login in it? If yes, then redirect it to the login.html page else logout.html page.

That’s it for now. We hope this article helped you to learn different redirects by JavaScript methods.

Additionally, read our guide:

  1. jQuery Form Submit With Examples
  2. Check If Array Is Empty Or Undefined In JavaScript
  3. How To Detect IE Browser In JavaScript
  4. AJAX PHP Post Request With Example
  5. How To Declare A Global Variable in Vue
  6. How To Remove A Specific Item From An Array In JavaScript
  7. How To Check Array Contains A Value In JavaScript
  8. How To Merge Objects In Vue

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you in advance 🙂. Keep Smiling! Happy Coding!

 
 

Leave a Comment

*

code