简体   繁体   中英

hide and show div only two divs at time with animation using JQuery

<div id="container">
                    <div id='div1' style="display:none;" class='cssdiv1'> 
                      <!-- content -->
                      <h1 style='color:#FFF7F7'>this is div 1 </h1>
                    </div>
                    <div id='div2'  style="display:none;" class='cssdiv2'> 
                      <!-- content -->
                      <h1 style='color:#FFF7F7'>this is div 2 </h1>
                    </div>
                    <div id='div3' style="display:none;" class='cssdiv3'> 
                      <!-- content -->
                      <h1 style='color:#FFF7F7'>this is div 3 </h1>
                    </div>
</div>

I have requirement where i want to show only two div's at a time and it should be in a loop.

You can loop using the length of the elements and with append() on Jquery like this:

 $(document).ready(function(){ var toloop = $('#container > div'), end = toloop.length-1, start = 0; toloop.eq(start).fadeIn(1000,shownext); function shownext() { start < end ? start++ : start=0; toloop.eq(start).fadeIn(1000); setTimeout(function(){ toloop.eq(start).prev().slideUp(800,function(){ $('#container').append($(this)) }); shownext(); },2000) } }) 
 #container > div { width:90%; margin:0 auto; padding:10px 20px; background:purple; color:white; display:none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <div><h1>this is div 1</h1></div> <div><h1>this is div 2</h1></div> <div><h1>this is div 3</h1></div> <div><h1>this is div 4</h1></div> <div><h1>this is div 5</h1></div> </div> 

Hope it helps.... * Changed the font color to improve readability

 var counter = 1 function toggleVisibility() { $("#div1, #div2, #div3").hide() $("#div"+ counter +", #div"+(counter+1)).fadeIn(500) if(counter < 2) counter++ else counter-- } toggleVisibility() setInterval(toggleVisibility, 5000) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="container"> <div id='div1' style="display:none;" class='cssdiv1'> <!-- content --> <h1 style='color:#323232'>this is div 1 </h1> </div> <div id='div2' style="display:none;" class='cssdiv2'> <!-- content --> <h1 style='color:#323232'>this is div 2 </h1> </div> <div id='div3' style="display:none;" class='cssdiv3'> <!-- content --> <h1 style='color:#323232'>this is div 3 </h1> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM