7703

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

0

58 Answers 58

1
2
45

Here is a time-delay redirection. You can set the delay time to whatever you want:

<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Your Document Title</title>
    <script type="text/javascript">
        function delayer(delay) {
            onLoad = setTimeout('window.location.href = "http://www.google.com/"', delay);
        }
    </script>
</head>

<body>
    <script>
        delayer(8000)
    </script>
    <div>You will be redirected in 8 seconds!</div>
</body>

</html>
0
44

There are three main ways to do this,

window.location.href='blaah.com';
window.location.assign('blaah.com');

and...

window.location.replace('blaah.com');

The last one is best, for a traditional redirect, because it will not save the page you went to before being redirected in your search history. However, if you just want to open a tab with JavaScript, you can use any of the above.1

EDIT: The window prefix is optional.

0
44

I just had to update this ridiculousness with yet another newer jQuery method:

var url = 'http://www.fiftywaystoleaveyourlocation.com';
$(location).prop('href', url);
0
38

Write the below code after the PHP, HTML or jQuery section. If in the middle of the PHP or HTML section, then use the <script> tag.

location.href = "http://google.com"
0
33

In jQuery, use $(location).attr('href', url):

$(document).ready(function(){
    var url = "https://www.youtube.com/watch?v=JwMKRevYa_M";
    $(location).attr('href', url); // Using this
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

In raw JavaScript, there are a number of ways to achieve that:

window.location.href="https://www.youtube.com/watch?v=JwMKRevYa_M";

- sets href property explicitly.

window.location = "http://www.GameOfThrones.com";

- does it implicitly Since window.location returns an object, which by default sets its .href property.

window.location.replace("http://www.stackoverflow.com");

- replaces the location of the current window with the new one.

self.location = "http://www.somewebsite.com";

- sets the location of the current window itself.

Here is an example of JavaScript redirecting after a certain time (3 seconds):

<script>
    setTimeout(function() {
        window.location.href = "https://www.youtube.com/";
    }, 3000);
</script>

0
27

In JavaScript and jQuery we use this following code to redirect the page:

window.location.href="http://google.com";
window.location.replace("page1.html");

But you can make a function in jQuery to redirect the page:

jQuery.fn.redirect=function(url)
{
    window.location.href=url;
}

And call this function:

jQuery(window).redirect("http://stackoverflow.com/")
3
  • 1
    Why are you passing window to the jQuery function in this line: jQuery(window).redirect(...)?
    – A1rPun
    Dec 4, 2015 at 18:55
  • @A1rPun what i need to pass window ord document ? Dec 4, 2015 at 22:20
  • 2
    This doesn't make sense as something that should be a jQuery method. There's no difference between $("div").redirect(url) and $().redirect(url). You could make it a static method, like $.redirect(url) but there's not really much need for that either. jQuery doesn't need to be involved at all.
    – 1j01
    Jul 9, 2016 at 22:10
26

Use the jQuery function:

$.extend({
  redirectPost: function(location, args) {
    var form = '';
    $.each(args, function(key, value) {
      form += '<input type="hidden" name="' + key + '" value="' + value + '">';
    });
    $('<form action="' + location + '" method="POST">' + form + '</form>').appendTo($(document.body)).submit();
  }
});

In your code you use it like this:

$.redirectPost("addPhotos.php", {pimreference:  $("#pimreference").val(), tag: $("#tag").val()});
24

Simply in JavaScript, you can redirect to a specific page by using the following:

window.location.replace("http://www.test.com");

Or

location.replace("http://www.test.com");

Or

window.location.href = "http://www.test.com";

Using jQuery:

$(window).attr("location","http://www.test.com");
0
21

You can use it like in the following code where getRequestToForwardPage is the request mapping (URL). You can also use your URL.

function savePopUp(){
    $.blockUI();
    $.ajax({
        url:"GuestHouseProcessor?roomType="+$("#roomType").val(),
        data: $("#popForm").serialize(),
        dataType: "json",
        error: (function() {
            alert("Server Error");
            $.unblockUI();
    }),
    success: function(map) {
        $("#layer1").hide();
        $.unblockUI();
        window.location = "getRequestToForwardPage";
    }
});

This is for the same context of the application.

If you want to use only jquery specific code then following code may help:

 $(location).attr('href',"http://www.google.com");
 $jq(window).attr("location","http://www.google.com");
 $(location).prop('href',"http://www.google.com"); 
0
19
<script type="text/javascript">
var url = "https://yourdomain.com";

// IE8 and lower fix
if (navigator.userAgent.match(/MSIE\s(?!9.0)/))
{
    var referLink = document.createElement("a");
    referLink.href = url;
    document.body.appendChild(referLink);
    referLink.click();
}

// All other browsers
else { window.location.replace(url); }
</script>
0
19

Using location.replace() will redirect you, but without saving the history of the previous page. This is better to use when a form is submitted.

But when you want to keep your history you have to use location.href=//path.

Examples:

// Form with steps
document.getElementById('#next').onclick = function() {
   window.location.href='/step2' // Iteration of steps;
}

// Go to next step
document.getElementById('#back').onclick = function() {
   window.history.back();
}

// Finish
document.getElementById('#finish').onclick = function() {
   window.location.href = '/success';
}

// On success page
window.onload = function() {
    setTimeout(function() {
       window.location.replace('/home'); // I can't go back to success page by pressing the back button
    },3000);
}
17

You can write the Url.Action for the Button click event in the script section as follows.

function onclick() {
    location.href = '@Url.Action("Index", "Home")';
}
0
16

Here is the code to redirect to some other page with a timeout of 10 seconds.

<script>
    function Redirect()
    {
        window.location="http://www.adarshkr.com";
    }

    document.write("You will be redirected to a new page in 10 seconds.");
    setTimeout('Redirect()', 10000);
</script>

You can also do it like this, on click of a button using location.assign:

<input type="button" value="Load new document" onclick="newPage()">
<script>
    function newPage() {
        window.location.assign("http://www.adarshkr.com")
    }
</script>
1
  • don't use inline click events. Bad practice and is not going to be supported in future iterations of all web browsers. Dec 18, 2014 at 16:54
16

This is very easy to implement. You can use:

window.location.href = "http://www.example.com/";

This will remember the history of the previous page. So one can go back by clicking on the browser's back button.

Or:

window.location.replace("http://www.example.com/");

This method does not remember the history of the previous page. The back button becomes disabled in this case.

16

If you prefer to use pure JavaScript I realized that using of document.location.href = "https://example.com" or window.location.href = "https://example.com" causes compatibility issues in Firefox. Instead try to use:

location.href = "https://example.com";
location.replace("http://example.com");

In my case has solved the problem. Good luck!

15

You can use:

window.location.replace("http://www.example.com/");

The replace() method does not save the originating page in the session history, so the user can't go back using the back button and again get redirected. NOTE: The browser back button will be deactivated in this case.

However, if you want an effect the same as clicking on a link you should go for:

window.location.href = "http://www.example.com/";

In this case, the browser back button will be active.

15
<script type="text/javascript">
    if(window.location.href === "http://stackoverflow.com") {      
         window.location.replace("https://www.google.co.in/");
       }
</script>
0
15

Single Page Application, within the same application route

window.location.pathname = '/stack';

JavaScript:

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

jQuery:

$(location).attr('href', "http://www.stack.com");
$(window).attr('location', "http://www.stack.com");

Angular 4

import { Router } from '@angular/router';
export class NavtabComponent{
    constructor(private router: Router) {
    }
    this.router.navigate(['bookings/taxi']);
}
14

Use:

function redirect(a) {
    location = a
}

And call it with: redirect([url]);

There's no need for the href after location, as it is implied.

14
  1. location.assign():

    To assign a route path by passing a path into it.. Assign will give you a history even after the path was assigned.

    Usage Method: value should be passed into it.

    For example: location.assign("http://google.com")

    Enter image description here

  2. location.href

    Can define give a path into it... And it will redirect into a given path once it setup, and it will keep history...

    Usage Method: value should be assign into it.

    For example: location.href = "http://google.com"

  3. location.replace():

    It will help to replace a path if you don't want to keep history. It won't give you a history once you replace its path.

    Usage Method: value should be pass into it.

    For example: location.replace("http://google.com")

    Enter image description here


assign() and href are similar, and both can hold history. assign will work by passing a value and href works by assigning.

You can achieve it using JavaScript itself without using jQuery by assigning,

window.location = "http://google.com"
location.href = "http://google.com"

You can achieve similar thing using jQuery like below. It will do exactly the same like above,

$(window).attr('location', "http://www.google.com");
$(location).attr('href', "http://www.google.com");

You can easily understand the difference between both...

Here is the Location object,

Location API from chrome

13

I just add another way:

To redirect for any specific page/links of your site to another page, just add this line of code:

<script>
    if(window.location.href == 'old_url')
    {
        window.location.href="new_url";
    }

    // Another URL redirect
    if(window.location.href == 'old_url2')
    {
        window.location.href="new_url2";
    }
</script>

For a real life example,

<script>
    if(window.location.href == 'https://old-site.com')
    {
        window.location.href="https://new-site.com";
    }

    // Another URL redirect
    if(window.location.href == 'https://old-site.com/simple-post.html')
    {
        window.location.href="https://new-site.com/simple-post.html";
    }
</script>

By using this simple code, you can redirect full site or any single page.

12

You can redirect the page by using the below methods:

  1. By using a meta tag in the head - <meta http-equiv="refresh" content="0;url=http://your-page-url.com" />. Note that content="0;... is used for after how many seconds you need to redirect the page

  2. By using JavaScript: window.location.href = "http://your-page-url.com";

  3. By using jQuery: $(location).attr('href', 'http://yourPage.com/');

4
  • There is no reason to use jQuery for this and window. is unnecessary.
    – 1j01
    Mar 9, 2017 at 17:30
  • Where i have used window. in jquery Query Example ? ... if you want to redirect the page through javascript ... than you need to use window.location..
    – SantoshK
    Mar 10, 2017 at 11:23
  • I meant those as separate things: you shouldn't use jQuery for this, and in the JavaScript example, you can simplify window.location.href = to location.href = or even location =.
    – 1j01
    Mar 16, 2017 at 23:34
  • Yes location.href = would be better option to redirect the page -:)
    – SantoshK
    Mar 21, 2017 at 11:01
10

I already use the function redirect() of JavaScript. It's working.

<script type="text/javascript">
    $(function () {
        //It's similar to HTTP redirect
        window.location.replace("http://www.Technomark.in");

        //It's similar to clicking on a link
        window.location.href = "Http://www.Technomark.in";
    })
</script>
1
  • 8
    what is the difference between this answer and the first ?
    – Mimouni
    Jun 17, 2016 at 12:47
10

If you want to redirect to a route within the same app simply

window.location.pathname = '/examplepath'

would be the way to go.

8

All way to make a redirect from the client side:

<!DOCTYPE html>
<html>
    <head>
        <title>JavaScript and jQuery example to redirect a page or URL </title>
    </head>
    <body>
        <div id="redirect">
            <h2>Redirecting to another page</h2>
        </div>

        <script src="scripts/jquery-1.6.2.min.js"></script>
        <script>
            // JavaScript code to redirect a URL
            window.location.replace("http://stackoverflow.com");
            // window.location.replace('http://code.shouttoday.com');

            // Another way to redirect page using JavaScript

            // window.location.assign('http://code.shouttoday.com');
            // window.location.href = 'http://code.shouttoday.com';
            // document.location.href = '/relativePath';

            //jQuery code to redirect a page or URL
            $(document).ready(function(){
                //var url = "http://code.shouttoday.com";
                //$(location).attr('href',url);
                // $(window).attr('location',url)
                //$(location).prop('href', url)
            });
        </script>
    </body>
</html>

7

Redirecting User using jQuery/JavaScript

By using the location object in jQuery or JavaScript we can redirect the user to another web page.

In jQuery

The code to redirect the user from one page to another is:

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

In JavaScript

The code to redirect the user from one page to another is:

var url = 'http://www.example.com';
window.location.href = url;

Or

var url = 'http://www.example.com';
window.location = url;
6

In my work experience, JavaScript is much better to redirect.

It depends on how you want to change the location. If you want to log your website in users history, use window.location.href='ur website';. Otherwise to do it without logging in history, use window.location.replace("your website");.

5

This is how I use it.

   window.location.replace('yourPage.aspx');   
   // If you're on root and redirection page is also on the root

   window.location.replace(window.location.host + '/subDirectory/yourPage.aspx');

   // If you're in sub directory and redirection page is also in some other sub directory.
1
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.