Kelvin Nielsen
Kelvin Nielsen

Reputation: 70

Show/Hide elements one by one repeatedly using jQuery

I am trying to show/hide a set of elements one by one repeatedly.

Following is the HTML:

<div id="1">Div 1</div>
<div id="2">Div 2</div>
<div id="5">Div 5</div>

I've tried the below script:

$(document).ready(function () {
    var repeat = function () {
        $('#1').show();
        $('#1').delay(1000).hide();
        $('#2').hide();
        $('#2').delay(1000).show();
        $('#2').delay(3000).hide();
        $('#5').hide();
        $('#5').delay(3000).show();
        $('#5').delay(6000).hide();
    };
    setInterval(repeat, 6000);
});

But I get all the divs visible at once. After the first 10 seconds everything hides and the script is done. Any pointers here is greatly appreciated.

Fiddle

Upvotes: 2

Views: 625

Answers (2)

Chetan
Chetan

Reputation: 5095

initially you are not setting the display propety to none. you should do that first so that it doesnt show up at once eg:

<div id="1" style="display:none;">Div 1</div>

Upvotes: 0

T J
T J

Reputation: 43166

If I understood correctly, You're looking for fadeToggle()

$(document).ready(function() {
  var repeat = function() {
    $('#1').fadeToggle(1000);
    $('#2').fadeToggle(1000);
    $('#5').fadeToggle(1000);
  };
  setInterval(repeat, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="1">Div 1</div>
<div id="2">Div 2</div>
<div id="5">Div 5</div>


If you want to display the elements one by one, You can use the complete callback of fadeToggle():

$(document).ready(function() {
  var repeat = function() {
    $('#1').fadeToggle(1000, function() {
      $('#2').fadeToggle(1000, function() {
        $('#5').fadeToggle(1000);
      });
    });

  };
  setInterval(repeat, 4000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="1">Div 1</div>
<div id="2">Div 2</div>
<div id="5">Div 5</div>

Upvotes: 1

Related Questions