How to avoid animation of elements that will not fit the width of the screen?

6

I created a jQuery animation for a customer's Christmas postcard. However, in 1024x768 or 800x600 resolution screens, elements appear in strange locations:

The code below hides the balls at startup, then makes them appear one by one until you can not find them:

// prepare balls
$('#balls img').each(function(){
    $(this).css({
        "opacity" :  0,
        "top"     : "-" + $(this).height() + "px"
    });
});

// animate balls
function gimeBalls(){

    $("#balls img:not('.done'):first").animate({
        "opacity" : 1,
        "top"     : 0
    }, 400, function() {
        $(this).addClass("done");
    });
}

setInterval(gimeBalls, 400);

Problem

As the images are all floated to the left, if the last image is not high enough to occupy the entire height of the container, the following image will look like the screenshot shown above.

Question

How can I with jQuery detect that the element to be displayed next will no longer fit the width of the screen, thus stopping the animation for all other elements?

See JSFiddle with a full example and working.

Note: If the bug is not visible, simply stretch or shrink the width of the preview square until you notice it. As the images are in my dropbox, the first access to the Fiddle is "strange" until the images have been downloaded.

Solution

The solution that can solve this, is to put all the balls in PNG with the height of the container where they are to be presented, thus finishing the spaces that cause this problem. However, this brings more download load to those who see the animation, so I would like to avoid this solution. On the other hand, by answering the question above, you can avoid animating elements that are not even visible.

    
asked by anonymous 20.12.2013 / 22:35

2 answers

4

Just modify the CSS by removing float and vertically aligning it to the top, updated example: link

#balls > img {
    display: inline-block;
    margin-left:28px;
    vertical-align: top;
}
    
20.12.2013 / 23:09
2

Here's a suggestion:

var wrapperWidth = $('#balls').width();
$('#balls img').each(function(){
    $(this).css({
        "top"     : "-" + $(this).height() + "px",
        "left"    : Math.floor(Math.random() * wrapperWidth) + "px"
    });
});

CSS:

#balls > img {
    margin-left:28px;
    position: absolute;
    opacity: 0;
/* removi  float:left; */
}

Example

What I've changed:

  • I removed opacity: 0; in jQuery, better to use in CSS for the balls to be hidden from the start (jQuery may take a long time to run and thus prevent the balls from appearing suddenly)
  • I added a random positioning of the balls with Math.floor(Math.random() * wrapperWidth) + "px"
  • I added a position: absolute; to the animate: top to work.
20.12.2013 / 23:12