1

Here my code:

$(document).ready(function() { $('#mid_select').live('click', function(e){ $('#middle').load( $(this).attr('href') + ' #middle'); var page = $(this).attr("rel"); alert(page); if (page == 'mywall'){ var auto_refresh = setInterval(function () { $('#bottom_middle').load('includes/main_middle_div.php?view=mywall #bottom_middle').fadeIn("slow");}, 5000); } else { clearInterval(auto_refresh); } e.preventDefault(); }); }); 

What I'm trying to do is, if the user clicks on a link with an id of #mid_select and a rel attribute that equals "mywall", then refresh the #bottom_middle div every 5 seconds, but if the user clicks on a link where the rel attribute does not equal "mypage" then don't refresh the #bottom_middle div every 5 seconds. Haven't been able to figure out how to get this done, help anyone?

1
  • Post your html on jsfiddle. You don't need this part: else { clearInterval(auto_refresh); } Commented Dec 23, 2011 at 23:45

1 Answer 1

2

You have to store a reference to the setIntervals timeout outside the click handler (using var). Also, you have to make sure that a maximum of one interval is looping at a time. The adjusted code, as shown below meets these criteria:

$(document).ready(function() { var auto_refresh = false; // Store this variable OUTSIDE the click handler $('#mid_select').live('click', function(e){ var $this = $(this); $('#middle').load( $this.attr('href') + ' #middle'); var page = $this.attr("rel"); alert(page); if (page == 'mywall'){ // Check whether an instance is already running... if (auto_refresh === false) { // NO var, because we use the auto_refresh var in the parent scope auto_refresh = setInterval(function () { $('#bottom_middle').load('includes/main_middle_div.php?view=mywall #bottom_middle').fadeIn("slow"); }, 5000); } else { // Clear interval, and explicitly set it to true clearInterval(auto_refresh); auto_refresh = false; } e.preventDefault(); }); }); 
Sign up to request clarification or add additional context in comments.

1 Comment

Yeah Rob, thanks, that works perfectly! One little thing, had to add a } to end the if (auto_refresh === false) { statement. Thanks again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.