tags:

views:

17

answers:

2

Hi ,

Is there any way in jquery to change the contents of a div based on timer.

Assume i have module to give "tips". The contents of the tips should change every 5 seconds.

Thanks

+2  A: 

Make an array of tips. Then make a interval of 5 seconds that change the div's content. I assume you want random tips.

See this example on jsFiddle.

var tips = [
    "Tip 01",
    "Tip 02",
    "Tip 03",
    "Tip 04",
    "Tip 05",
    "Tip 06",
    "Tip 07",
    "Tip 08",
    "Tip 09"
];

// get a random index, get the value from array and
// change the div content
setInterval(function() {
    var i = Math.round((Math.random()) * tips.length);
    if (i == tips.length) --i;
    $("#tip").html(tips[i]);
}, 5 * 1000);

See:

BrunoLM
@bruno Perfect thank you very much.Excellent.
gov
+2  A: 

javascript has a method called .setInterval(), which will run code every n milliseconds.

var $div = $('#myDiv');

var timer = setInterval( function() {
    $div.html( newContent ); // which would reference some dynamic content 
}, 5000);

By storing the return value of .setInterval() in a variable, you can stop the interval later by using .clearInterval().

clearInterval( timer );
patrick dw
@patrick.Thank you very much
gov
@gov - You're welcome. :o)
patrick dw
@patrick,this site is really awesome, whenever i stuck in development , if i post doubt i am getting answer with in fraction of seconds.I started UI development very recently like 8 months back only.
gov