views:

157

answers:

2

The code of the first function shows three different divs on specific Interval 5seconds (div1,div2,div3).
The code of the second function used to stop showing the divs.

while showing div2 , I clicked the link to stop at that point it got stopped.
But after that i clicked it again and it shows div1 (its getting toggling fine) but i would like to continue next action which was to show div3.

Jquery Code :

$(function() {

 var IntervalId;

 function first_function() {
 var counter = 0,
 divs = $('#div1,#div2,#div3');
 function showDiv () {
           divs.hide() // hide all divs
          .filter(function (index) { return index == counter % 3; }) 
          .show('fast'); // and show it
          counter++;
 }; 
 showDiv();     
 IntervalId = setInterval(showDiv, 5000);
 }; 

 function second_function(){  
  clearInterval(IntervalId); 
 }  

 $("#link1").toggle(
 first_function,second_function
 );

});

Html Code :

<a href="javascript:void(0);" id="link1">Toggle</a>
+2  A: 

move the initialization of counter outside first_function():

$(function() {

 var IntervalId;
 var counter = 0,

 function first_function() {
 divs = $('#div1,#div2,#div3');
 ...

In your example, every time you call first_function(), the counter is set back to zero.

Philippe Leybaert
Thanks activa +1
Webrsk
A: 

Have fun with:

<script type="text/javascript">
$(function() {
  var divFunctions = [];
  var $divs = $('#div1,#div2,#div3');

  $divs.each(function() {
    var $this = $(this);
    divFunctions.push(function() {
      return function() {
        $divs.not($this).hide();
        $this.show("fast")
      };
    }());
  });

  var $toggle_button = $("#link1");
  $toggle_button.toggle.apply($toggle_button, divFunctions);
});
</script>

<body>
  <a href="javascript:void(0);" id="link1">Toggle</a>

  <div id='div1' style="display:none;">content1</div>
  <div id='div2' style="display:none;">content2</div>
  <div id='div3' style="display:none;">content3</div>
</body>
Tomalak