Wednesday 18 September 2013

URL redirection from One page to another page using jQuery

There are multiple ways to redirect one web page to another by using javascript & jquery.

Method 1:
1
window.location.href = "http://jqueryexamples4u.blogspot.in";

Method 2:
1
window.location.replace("http://jqueryexamples4u.blogspot.in");

Note: REPLACE method - won't store History about previous page. it breaks the back button behavior  i.e, if you redirects to a new address instead of window.location.replace("..") method, if you where to hit the back button in your browser once you've been redirected, you will go back to the redirecting page, and the redirecting page will redirect you back to the new address. It will act as an endless circle.

Method 3:

1
$(location).attr('href',url);

or

1
$(window).attr("location","http://jqueryexamples4u.blogspot.in");

Additionally,

You must have came across any website which uses a webpage with some annoying advertisement and a message that says "You will be redirected to actual page after "Some X" seconds". This can be easily implemented with jQuery. below simple jQuery code to redirect user to another webpage after specific amount of time (seconds).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$(function () {
    window.setInterval(function () {
        var startingSeconds = $(".secondsCount").text();
        startingSeconds = eval(startingSeconds);
        if (startingSeconds == 0) {
            location.href = "http://jqueryexamples4u.blogspot.in";
        } else {
            // decrease seconds counts by 1
            $(".secondsCount").text(startingSeconds - 1);
        }
    }, 1000);
});

We can achive above result, by If (redirect in a set amount of time) meta refresh tag, like this.
1
<meta http-equiv="refresh" content="10" url="http://jqueryexamples4u.blogspot.in">

Just replace the http://jqueryexamples4u.blogspot.in with the actual address of the page you want to redirect to.

Next, change the content="10" to the number of seconds you want it to take before the page refresh.

No comments:

Post a Comment