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

Fade in elements

Hello guys...

I found this JS that will allow me to fadein element when it is visible in browser, but it can only fade in everything at the same time, I have 3 elements one next to each other that I want to fade in in simple order and not all at the same time...

How can I do that?

$(document).ready(function() {

    /* Every time the window is scrolled ... */
    $(window).scroll( function(){

        /* Check the location of each desired element */
        $('.fadein').each( function(i){

            var bottom_of_object = $(this).position().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height();

            /* If the object is completely visible in the window, fade it it */
            if( bottom_of_window > bottom_of_object ){

                $(this).animate({'opacity':'1'},1000);

            }

        }); 

    });

});

2 Answers

Mark Josephsen
Mark Josephsen
8,803 Points

I think it is doing them in order, just really fast that you don't notice. I'd add a delay in your array. Maybe chain .delay(100) to the end of your .animate()

J Scott Erickson
J Scott Erickson
11,883 Points

Mark is correct in saying that the function call are happening in order, but that they are happening quickly. His solution would work as well I believe.

Hey, thank you for comment, I just tried this but it is not working, did I wrote code correctly?

$(this).animate({'opacity':'1'},1000).delay(1000);
Mark Josephsen
Mark Josephsen
8,803 Points

Dang. Perhaps Scott's solution of nesting will do the trick. Do you have a JSFiddle?

Yes, it is tomicicivan...

J Scott Erickson
J Scott Erickson
11,883 Points

The easiest way would be to nest within the complete method call in your function:

You could have named functions for each element if you don't like the look of it nested like that.

$(this).animate({'opacity':'1'},1000, function () {
  $('other item').animate({'opacity':'1'},1000, function(){
    $('other item').animate({'opacity':'1'},1000)
  })
});