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!
// 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.
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/
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With