Reputation: 5463
So I have a div that can have several divs inside of it. Something like:
<div id="news">
<span>Latest News!</span>
<div>
//News 1
</div>
<div>
//News 2
</div>
</div>
What I'm trying to do is on page load, the first div is visible, then after so many seconds, it fades out and the second div fades in. Pretty simple with fadeIn and fadeOut but I have to specifiy each div's actions. Is there a way to say 'Toggle between every div inside my #news div'? This way I can add new divs without having to add code to hide/show them?
Thanks!
Upvotes: 6
Views: 704
Reputation: 4314
This will loop through the news items. When it reaches the end, it'll start back at the top. Change the 2000 to whatever interval you want (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 working example.
Upvotes: 1
Reputation: 754545
Try the following
$(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/
Upvotes: 2
Reputation: 342625
// 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);
Upvotes: 3
Reputation: 30095
Probably you need some plugin with content rotation.
Here is one of them: http://demo.smartnetzone.com/auto-rotating-tabs-using-jquery/
Upvotes: 1
Reputation: 3167
You may also want to look into using the jQuery Cycle plugin:
http://jquery.malsup.com/cycle/
Upvotes: 1
Reputation: 17960
You could try using jQueryUI, which has a tab control: http://jqueryui.com/demos/tabs/
Otherwise you could give all the divs a common class, say "tab". Then for your tab buttons you can just have:
$(".tab").fadeOut();
$("#tab-that-I-want").fadeIn();
Upvotes: 1