Skip to content
Related Articles

Related Articles

How to redirect to a relative URL in JavaScript?
  • Last Updated : 31 Oct, 2019

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

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!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>

    chevron_right

    
    

    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

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!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>

    chevron_right

    
    

    Output:

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

  • full-stack-img

    My Personal Notes arrow_drop_up
Recommended Articles
Page :