0

i have these two divs and would like to know how can i display the second (box2) div every 3 seconds.

<div id="box1" style="background-color:#0000FF">
     <h3>This is a heading in a div element</h3>

    <p>This is some text in a div element.</p>
</div>
<div id="box2" style="background-color:red">
     <h3>This is a heading in a div element</h3>

how can i do this with jquery ?

i created a fiddle here. http://jsfiddle.net/jRmrp/5/

Update 1

The answer given by Khanh TO works but i am wondering what to do when div count is more than 2. it only allows for two.

dev1234
  • 5,376
  • 15
  • 56
  • 115

2 Answers2

4

You need this?

setInterval(function(){
     $("#box2").toggle();
    $("#box1").toggle();
},3000);

DEMO

Updated with new requirement:

var currentIndex = 0;
$(".box:not(:eq("+ currentIndex +"))").hide();

var totalDiv = $(".box").length;

setInterval(function(){
     currentIndex = (currentIndex + 1) % totalDiv;

    $(".box").hide();
     $(".box").eq(currentIndex).show();

},3000);

DEMO

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
  • what can i do when i have more than 2 divs ? lets say 3 divs and each should display and hide one after one with in given time. appreciate if you can show me through fiddler – dev1234 Nov 23 '13 at 12:02
  • 1
    Nice solution Khanh +1 – cssyphus Nov 23 '13 at 16:45
  • @KhanhTO .toggle() is deprecated. could you please provide a better way to do it. toggle causes me this problem. http://stackoverflow.com/questions/20195189/jquery-toggle-function-is-not-working-with-hoverwords-sliding-letters-extens – dev1234 Nov 25 '13 at 14:24
  • @mazraara: .toggle is for the first solution. You could try the updated general solution without using toggle. – Khanh TO Nov 26 '13 at 02:26
  • @mazraara: or you could try my updated solution 1 without using toggle. – Khanh TO Nov 26 '13 at 02:35
  • @mazraara: after reading jQuery docs, I found out that what is deprecated is the toggle event, not toggle function. Could you show me the docs saying toggle function is deprecated? – Khanh TO Nov 26 '13 at 03:26
  • @KhanhTO check here http://api.jquery.com/toggle-event/ and thanks for the first solution. – dev1234 Nov 26 '13 at 03:48
  • @mazraara: that's the toggle event, not the toggle function. toggle function us here http://api.jquery.com/toggle/ – Khanh TO Nov 26 '13 at 03:48
  • @KhanhTO Oppz, my bad. i am sorry about it then. can you help me this pls http://stackoverflow.com/questions/20195189/jquery-toggle-function-is-not-working-with-hoverwords-sliding-letters-extens – dev1234 Nov 26 '13 at 04:11
2

jsFiddle demo

doBoxBlink = setInterval(blink, 1500);

function blink() {
    $('#box2').toggle();
}
cssyphus
  • 37,875
  • 18
  • 96
  • 111