Skip to content
Related Articles
Open in App
Not now

Related Articles

How to redirect to a relative URL in JavaScript?

Improve Article
Save Article
  • Difficulty Level : Expert
  • Last Updated : 31 Oct, 2019
Improve Article
Save Article

This works in the same way as redirecting to any URL in javascript.

  • Approach 1: To redirect to a relative URL in JavaScript you can use
    window.location.href = '/path';

    window.location.href returns the href (URL) of the current page

    Example 1: A simple redirecting program




    <!DOCTYPE html>
    <html>
    <head>
      <script>
        function newLocation() {
            window.location.href="page.html";
        }
      </script>
    </head>
    <body>
      <input type="button" value="Go to new location" onclick="newLocation()">
    </body>
    </html>

    Output:

  • Approach 2: To redirect to a relative url you can use
    document.location.href = '../';

    Both windows.location.href and document.location.href are same.

    Example 2: A simple redirecting program




    <!DOCTYPE html>
    <html>
    <head>
      <script>
        function newLocation() {
            document.location.href="page.html";
        }
      </script>
    </head>
    <body>
      <input type="button" value="Go to new location" onclick="newLocation()">
    </body>
    </html>

    Output:

    NOTE: You can use both methods but for cross browser safety first one is preferred.


  • My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!