willoller
willoller

Reputation: 7322

jquery animation with nested effects loop

I have a nested function to show/hide paragraphs news-ticker-style.

The problem is that when the loop starts over (line 4), the opacity effects stop working correctly so the paragraphs appear abruptly.

Any jquery masters know about this? Am I making this too hard?

$('#special-ticker p').hide();
var a=0;
function outer() {
    function inner() {
        if(a===$('#special-ticker p').length) { a = 0; }
        $('#special-ticker p').
        eq(a).
        fadeIn(800, function(){
            $(this).animate({opacity:100},10000,null,function(){
                $(this).hide(800,function(){
                    a++;
                    outer();
                });
            });
        });
    }
    return inner();
}
$(function(){ 
    outer(); 
});

Upvotes: 4

Views: 7541

Answers (4)

Jason Moore
Jason Moore

Reputation: 7195

A slight reworking of the code to save repeatedly creating jQuery instances with the same selectors. I think it's a little easier to read, too.

var jS = $('#special-ticker p');
// jS.hide(); // not needed if css hides elements initially
var i = 0;

function do_ticker() {
  jS.eq(i).fadeIn(800, function() {
    var me = $(this);     
    setTimeout(function() { me.hide(800, 
      function() { 
        i = ++i % jS.length;
        do_ticker();
      });
    },1000); // setTimeout
  });
};
do_ticker();

Upvotes: 1

Jason Moore
Jason Moore

Reputation: 7195

Solution has been posted, but one comment:

If a group of elements are going to be hidden immediately, it is faster to create a "hidden" CSS class and then assign it to those elements. Saves a bit of javascript code, but also ensures that the hidden elements won't be briefly flashed on screen.

<style type="text/css" media="screen">
.hidden { display: none; }
</style>

<p>Show me</p>
<p class="big hidden">Use javascript to show me later.</p>

Upvotes: 1

Andy
Andy

Reputation: 679

Try this:


            newsticker = function (selector) {
                $(selector).hide();
                var i = $(selector).length - 1;
                var toggle = function() {
                    $(selector).eq(i).fadeOut("slow", function() {
                        i = ++i % $(selector).length;
                        $(selector).eq(i).fadeIn("slow", function() {
                            setTimeout(toggle, 1000)
                        });

                    });
                };          
                toggle();
            };

and initialize it with this:


            new newsticker("#special-ticker p");

Upvotes: 1

Owen
Owen

Reputation: 84493

the problem is line 9:

$(this).animate({opacity:100},10000,null,function(){
//...

opacity should be "1" (opacity is a value between 0 and 1)

$(this).animate({ opacity : 1 }, 10000, null, function() {

Upvotes: 5

Related Questions