Monday, 16 February 2015

Automatically Refresh HTML page or div after specific time Interval

There are several ways to refresh a complete HTML page after specific time interval, and same is the case with any specific Div or Span or any HTML element on a page, that we can refresh any specific part/element of HTML page without reloading the complete page.
First let’s take a look at refreshing HTML page after specific time interval, this can be achieved using either JavaScript or by meta tags.
A) Using Javascript:
You can use either of the following scripts to refresh after every 5 secounds, say:


Code I:

<script>

function autoRefresh()
{
window.location = window.location.href;
}

setInterval('autoRefresh()', 5000); // this will reload page after every 5 secounds; Method I
</script>

OR
Code II:


<script>

function autoRefresh1()
{
   window.location.reload();
}

setInterval('autoRefresh1()', 5000); // this will reload page after every 5 secounds; Method II
</script>

B) Refresh page using Meta tags
Its very easy, you just have to put a meta tag in head tag as follows:


<head>

<meta http-equiv="refresh" content="5" />
    <!-- This will refresh page in every 5 seconds, change content= x to refresh page after x seconds -->
</head>

Refresh Div/Span on HTML page after specific time:
In this part we will use JQuery to perform the task, as its provides few of the best options that can help us.
Suppose you have a div with ID as result similar to following:


<div id="result"></div>
Then JQuery code will be as follows:


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function autoRefresh_div()
{
    $("#result").load("load.html");// a function which will load data from other file after x seconds
}

setInterval('autoRefresh_div()', 5000); // refresh div after 5 secs
</script>

Similarly you can use $.ajax() or $.post() etc instead of load() function and put the response in a div or a span.
— Automatically Refresh HTML page or div after specific time Interval –

No comments:

Post a Comment