Sunday, April 19, 2009

Dynamically changing/displaying web page content using javascript without refreshing the page

Sometimes we may need to change the content displayed in the webpage frequently.
Javascript will enable achieving this without the need for refreshing the webpage.(i-e without requesting the page again).

Below steps are needed for doing this.
- All the contents should be stored in a Javascript array.
- Body onLoad event will call a function thro' a javascript method setInterval().
- setInterval() method will behave similar to setTiemout() which will call a function after preset time. Additionally setInterval() will call the function repeatedly.

You can refer the below code. This blog is using the similar code for displaying Quotes in side bar.

<script type="text/javascript">
var quoteIntervalId = 0;
var arrQuotes=[
function displayQuote ( )
quoteIntervalId = setInterval ( "showQuote()", 1000 );

function showQuote ( )
var randnumber=Math.random ( )*1000;
var count_quotes=arrQuotes.length;
var quoteindex=randnumber%count_quotes;
document.getElementById("quotemsg").innerHTML = arrQuotes[quoteindex];

<body onLoad="displayQuote();">
<div id="quotemsg"></div>


- arrQuotes is a javascript array used for storing all the content when requesting the page.
-Call displayQuote() function from onLoad event of body tag.

- The displayQuote()function uses setInterval() to call another function showQuote after 1000 milli seconds (1 second) repeatedly.

- The showQuote() function uses Math.random() to generate a random number, and used modulo operator(%) to normalize/limit the random number within the number of items in the arrQuotes array.

- Take the content from the array based on this normalized random number and InnterHTML of a div tag ( with id quotemsg) is set with this content.
More Articles...

1 comment:

Anonymous said...

With simplicity in presentation, the article was useful, Thank you !

Search This Blog