Search code examples
javascriptjqueryimageanimationjquery-animate

Making a set of images move cross the screen then when leaving the window, it comes up from the other side


I'm trying to implement the marquee tag in jQuery by animation a set of images using animate() function, making them move to the right or left direction.
But, I couldn't figure out when a single image goes to the end of the screen returns individually to the other side.
Because I heard that the window size is not constant for every browser, So is there anyway to implement that?
this is what I came up so far(it's simple and basic):

$(document).ready(function(){
    moveThumbs(500);
    function moveThumbs(speed){
        $('.thumbnails').animate({
            right:"+=150"
        }, speed);
        setTimeout(moveThumbs, speed);
    }

});

note: I searched in SO for related questions, but had no luck to find exact information for my specific issue.


Solution

  • Here's a basic script that moves an image across the screen and then resumes on the other side and adapts to the window width.

    You can see it working here: http://jsfiddle.net/jfriend00/rnWa2/

    function startMoving(img) {
        var img$ = $(img);
        var imgWidth = img$.width();
        var screenWidth = $(window).width();
        var amount = screenWidth - (parseInt(img$.css("left"), 10) || 0);
        // if already past right edge, reset to 
        // just left of left edge
        if (amount <=0 ) {
            img$.css("left", -imgWidth);
            amount = screenWidth + imgWidth;
        }
        var moveRate = 300;   // pixels per second to move
        var time = amount * 1000 / moveRate;
        img$.stop(true)
            .animate({left: "+=" + amount}, time, "linear", function() {
                // when animation finishes, start over
                startMoving(this);
            })
    }
    
    $(document).ready(function() {
        // readjust if window changes size
        $(window).resize(function() {
            $(".mover").each(function() {
                startMoving(this);
            });
        });
    });
    

    ​ ​