Latest News!...">

Switch between divs in another div using jQuery?

So, I have a div that can have multiple divs inside. Sort of:

<div id="news"> <span>Latest News!</span> <div> //News 1 </div> <div> //News 2 </div> </div> 

What I'm trying to do is load the page, the first div is visible, and then after a few seconds it disappears, and the second div disappears. Pretty simple with fadeIn and fadeOut, but I have to specify each action div. Is there a way to say "Switch between each div inside my #news div"? So I can add new divs without adding code to hide / show them?

Thanks!

+6
source share
6 answers

Try to execute

 $(document).ready(function() { $('#news div:gt(0)').hide(); var swap = function(item) { setTimeout(function() { $(item).fadeOut(1000, function() { var next = $(item).next()[0]; if (!next) { next = $('#news div')[0]; } $(next).fadeIn(1000, function() { swap($(this)[0]); }) }); }, 1000); }; swap($('#news div')[0]); }); 

Fiddle: http://jsfiddle.net/9gwzt/2/

+2
source
 // count the number of news items var len = $("#news div").length; // hide all but the first $("#news div:gt(0)").hide(); // set up a counter var counter = 0; // function to hide all except the current iteration function changeDiv() { $("#news div").eq(counter).show().siblings("div").hide(); counter++; // when we reach the last one, start again if(counter === len) { counter = 0; } } // go! var i = setInterval(changeDiv, 2000); 

Demo

+3
source

You can try using jQueryUI, which has a tab control: http://jqueryui.com/demos/tabs/

Otherwise, you can give all divs a common class, such as "tab". Then for your tab buttons you can simply:

 $(".tab").fadeOut(); $("#tab-that-I-want").fadeIn(); 
+1
source

You can also learn about using the jQuery Cycle plugin:

http://jquery.malsup.com/cycle/

+1
source

Perhaps you need a content rotation plugin.

Here is one of them: http://demo.smartnetzone.com/auto-rotating-tabs-using-jquery/

+1
source

This will lead to viewing the news. When he reaches the end, he will return above. Change 2000 to any desired interval (in ms).

 function switchNewsItem(){ $('#news div:visible').fadeOut(function(){ $(this).next().length ? $(this).next().fadeIn() : $('#news div').eq(0).fadeIn(); }); }; $('#news div').eq(0).show(); // show the first news item setInterval(switchNewsItem, 2000); 

See a working example .

+1
source

Source: https://habr.com/ru/post/897841/


All Articles