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.
<html>
<head>
<script type="text/javascript">
var quoteIntervalId = 0;
var arrQuotes=[
'quote1',
'quote2',
'quote3',
'quote4'];
function displayQuote ( )
{
quoteIntervalId = setInterval ( "showQuote()", 1000 );
}
function showQuote ( )
{
var randnumber=Math.random ( )*1000;
randnumber=parseInt(randnumber);
var count_quotes=arrQuotes.length;
var quoteindex=randnumber%count_quotes;
document.getElementById("quotemsg").innerHTML = arrQuotes[quoteindex];
}
</script>
</head>
<body onLoad="displayQuote();">
<div id="quotemsg"></div>
</body>
</html>
Here,
- 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:
With simplicity in presentation, the article was useful, Thank you !
Post a Comment