jqueryeachfadeoutfadeto

jQuery: fadeTo/fadeOut items from a PHP Loop


So I am completly new to jQuery. And I have been trying with this all day without any success yet.

I have a php loop containing divs and what I want to do is to fadeIn the first item, fade it out, then fadein the next and so on.

So far I have come up with this:

And then it was time for jQuery for fadeIn/fadeOut. Since I start with opacity 0.0 it seems that I can not use fadeIn so I use fadeTo instead. I then figured I had to asign ID's to all the div's since I dont know how many items the loop contains. And then use .each to fadeTo/fadeOut each item.

But I can't get it right. Obviously I am doing some thing wrong.

This is the jQuery I came up with:

$(document).ready(function() {
    $( '#container div' ).each( function(i) {
        $(this).attr('id', 'item-'+(i+1) );
    });

    $( '#container div' ).each( function(i) {
        $( '#item-'+(i+1) ).fadeTo(3000, 1).delay(3000).fadeOut('slow');
    });
});

I should also say, that in this case I can't asign ID with the PHP loop, and then get them with jQuery. The Id's need to be asign using jQuery.


Solution

  • One of countless solutions:

    function slide() {
    $( '#container div:first' ).fadeTo(3000, 1).fadeTo(1000,0, function() {
    $( "#container" ).append( '<div>'+$(this).html()+'</div>' );
    $(this).remove();
    });
    }
    
    setInterval(slide,1000);
    

    To get idea what is happening here, check demo: http://jsfiddle.net/1xzw6fw0/, and turn on inspector and inspect HTML (F12 on Win systems, i am using Web developer tools in Firefox).

    Idea is: fade in JUST first element in container, then when it is hidden/animation complete/opacity:0 - you see additional function as parameter of fadeTo() - that function append it to the END of container, and removes current element from DOM, so now first element is last, second is first, etc, etc...

    Hope you got it? And at the end - we will call function slide() every second - you can change it to fit your needs...