Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle between divs inside another div using jQuery?

Tags:

jquery

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!

like image 418
ItsPronounced Avatar asked Sep 22 '11 16:09

ItsPronounced


3 Answers

// 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.

like image 147
karim79 Avatar answered Sep 22 '22 05:09

karim79


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/

like image 39
JaredPar Avatar answered Sep 22 '22 05:09

JaredPar


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();
like image 40
robbrit Avatar answered Sep 19 '22 05:09

robbrit