In this article I will explain how to redirect to another page (HTML page) after delay of some time (say 5 seconds or 10 seconds) using jQuery.
The JavaScript setInterval function will be used to redirect to another page after delay of some time using Query.
Redirect to another page after delay 5 seconds using jQuery
The following HTML Markup consists of an HTML Button and an HTML DIV containing an HTML SPAN for displaying the Countdown timer. The Button has been assigned a jQuery click event handler.
Inside this click event handler, the JavaScript setInterval function is initialized to execute every 1000 milliseconds i.e. every one second.
Every time the JavaScript setInterval function is executed, it first decrements the value of seconds variable then displays its value in Countdown timer HTML SPAN and when the value of the seconds variable is 0, the Countdown timer ends and the page is redirected to another page.
<input type="button" id="btnRedirect" value="Redirect" />
<br />
<br />
<div id="dvCountDown" style="display: none">
You will be redirected after <span id="lblCount"></span> seconds.
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnRedirect").click(function () {
var seconds = 5;
$("#dvCountDown").show();
$("#lblCount").html(seconds);
setInterval(function () {
seconds--;
$("#lblCount").html(seconds);
if (seconds == 0) {
$("#dvCountDown").hide();
window.location = "http://www.jqueryfaqs.com/";
}
}, 1000);
});
});
</script>
Screenshot
Browser Compatibility
The
above code has been tested in the following browsers.
* All
browser logos displayed above are property of their respective owners.
Demo
Downloads
Redirect_Delay_jQuery.zip