Russell Parrott Russell Parrott - 3 months ago 19
jQuery Question

JQuery auto refresh (setInterval)

Hi folks not sure the best way to do this - i.e. where to put the

if
's .. I have a div that loads a page and has a setInterval() function.

On the loaded page there is 1 button, What I want to acheive is when button #1 (loaded page) is clicked to stop the setInterval() and append a new div (position absolute) until button#2 (on the apended div) is clicked then to restart it. .. comprende?

Here is my "base" code

This is the action from the first button

$('.replybutton').live('click',function(){
$('.discussion').append('<div class="replyarea">some content in here plus "button number2</div>');
});


This loads the page - initially

$('.discussion').load('board2.php');


And this is the refresh function

var auto_refresh = setInterval(
function()
{
$('.discussion').fadeOut().load('board2.php').fadeIn();

}, 10000);


Failing anything - (but NOT preferred) I could use a toggle on the loaded page rather than the append used in the
$('.replybutton').live('click',function()
, but would still need to stop the refresh and restart it - based on the toggle, but I stress the toggle idea is not the preferred way.

Answer

I created an example for you at JSFiddle. Check it out here: http://jsfiddle.net/7YYV7/.

Code

var intervalId = 0;
intervalId = setInterval(fadeDiscussion, 3000);

$(function() {
    $('input[name=click]').bind('click', function() {
        clearInterval(intervalId);     

        $('.discussion').append('<div class="replyarea">some content in here plus <input type="button" name="save" value="save"></div>');    
    });

    $('input[name=save]').live('click', function() {
         intervalId = setInterval(fadeDiscussion, 3000);   
    });
});

var i = 1;
function fadeDiscussion () {
    console.log(i);
    $('.discussion').fadeOut().fadeIn();
    i++;
}
Comments