Undefined
Undefined

Reputation: 11431

jQuery Loop Function doesn't appear to be working

I'm having a problem with a div that fades into the page on slide 12 of an HTML/jQuery presentation.

When running the below code the div will fade in but will not follow the function called loop and repeat itself. It should fade to 50% opacity and back to 100% in a continuous loop.

I'm fairly confident the issue is with my syntax, but I've had no luck yet.

jQuery:

// if slide 12
if (index == 11) {
    $("#prev").show();
    $("#next").show();
    $("#p12-1").delay(2000).fadeIn("slow", function() {
        function loop() {
            $("#p12-1").delay(200).fadeTo("slow", 0.5, function ()  {
                $("#p12-1").delay(200).fadeTo("slow", 1, loop);
            });
        };
    });
    createParticles($("#main").offset().left + 200, $("#main").offset().top + 100, 4000);
}

HTML:

<div class="main-slide main-slide-12" style="display:none;">
<div id="p12-1" style="display:none;"><img src="images/p12-1.png" /></div>
<div style="display:none;" id="p12-2"><img src="images/p12-2.png" /></div>
<div style="display:none;" id="p12-3"><img src="images/p12-3.png" /></div>

Upvotes: 1

Views: 157

Answers (2)

Yoshi
Yoshi

Reputation: 54649

Change:

$("#p12-1").delay(2000).fadeIn("slow", function() {
    function loop() {
        $("#p12-1").delay(200).fadeTo("slow", 0.5, function ()  {
            $("#p12-1").delay(200).fadeTo("slow", 1, loop);
        });
    };
});

to:

$("#p12-1").delay(2000).fadeIn("slow", function() {
    (function loop() {
        $("#p12-1").delay(200).fadeTo("slow", 0.5, function ()  {
            $("#p12-1").delay(200).fadeTo("slow", 1, loop);
        });
    }());
});

Little update:

In general it is not needed to queue animations on the same elements using the oncomplete-callback. This said, you could also use code like this, with the same effect (note that you could chain as many animations and delays as you want, and only use fade as the last on-complete callback to start over):

(function fade () {
  $('#p12-1')
  .delay(2000)
  .fadeIn('slow')
  .delay(2000)
  .fadeOut('slow', fade);
}());

Demo: http://jsfiddle.net/TPBFt/

Upvotes: 3

ThiefMaster
ThiefMaster

Reputation: 318488

Replace

$("#p12-1").delay(2000).fadeIn("slow", function() {
    function loop() {
        $("#p12-1").delay(200).fadeTo("slow", 0.5, function ()  {
            $("#p12-1").delay(200).fadeTo("slow", 1, loop);
        });
    };
});

with

$("#p12-1").delay(2000).fadeIn("slow", function() {
    function loop() {
        $("#p12-1").delay(200).fadeTo("slow", 0.5, function ()  {
            $("#p12-1").delay(200).fadeTo("slow", 1, loop);
        });
    }
    loop();
});

I didn't use a function expression like @Yoshi did since AFAIK some browser do not like named function expressions.

Upvotes: 0

Related Questions