Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

JQuery fadeTo() function not working

Hey, I have a problem with the JQuery function fadeTo(). Here is the example: http://jsfiddle.net/mnlfischer/YFz38/. When delete the else, it is working, but I want to set the opacity back to 0 if the scrollbar is out of the area. I wont use the hide() show() functions cause they dont keep the original height of a div. (I need the placeholder in a fluid design). Someone can help me? Thank you!

2 Answers

The scroll event is calling your fadeTo() animations numerous times. They're piling up and executing one after the other. If you actually wait a bit, you'll see the fade-ins and fade-outs. I actually fiddled a bit with the code to check that no animations are being repeated needlessly. I hope it is what you're looking for:

<script type="text/javascript">
    var fadingIn = false;
    var fadingOut = false;
    $(document).scroll(function() {
        var $scrollVal = $(this).scrollTop();
        if ($scrollVal > 10 && $scrollVal < 550) {
            //Check if there is an ongoing fade-in. If so, do not animate        
            if (!fadingIn) {
                $("#inner").fadeTo("slow", 1, function() {
                    //Reset the fade-in flag when the animation is over
                    fadingIn = false;
                });
                fadingIn = true;
            }
        } else {
            if (!fadingOut) {
                $("#inner").fadeTo("slow", 0, function() {
                    fadingOut = false;
                });
                fadingOut = true;
            }
        }

    });
</script>

awesome work, thanks man!