[Solved] How to animate a div move horizontally when page is scroll down? [closed]


Since you included the jQuery tag, I’ll give you a jQuery-based solution. First, let’s set up some structure for the example:

HTML

<div class="sample red"></div>
<div class="sample green"></div>
<div class="sample blue"></div>
<br>
<div class="new">aaa</div>

The three “sample” divs are the ones that’ll animate as we scroll. “new” is the content.

CSS

.sample {
    width:100px;
    height:300px;
    position:fixed;
    left:-102px;
    background:red
}
.green {
    background:green; top: 30px;
}
.blue {
    background:blue; top: 60px;
}
.new {
    margin-top:1000px
}

This just ensures there’s actually some scrolling possible (1000px-high content) and sets up the styles and positions for the sample divs (fixed positions, all docked to the left, different background colors and vertical positions).

Now, we can listen for the scroll event and animate accordingly:

Script

// cancels any existing animations 
// and animates the "slide out" transition for all samples
function hideDivs() {
    $('.sample').stop().animate({
        left: '-102px'
    }, 1000);
}

// slides in various samples for various scroll positions
// hides any that aren't appropriate for the current position
function showDivs() {
    hideDivs();
    var top = $(document).scrollTop();
    if ( top >= 100 && top < 300 ) {
        $('.red').stop().animate({
            'left': '0px'
        }, 1000);
    } else if (top >= 300 && top < 500) {
        $('.green').stop().animate({
            'left': '0px'
        }, 1000);
    } else if (top >= 500) {
        $('.blue').stop().animate({
            'left': '0px'
        }, 1000);
    } 

}

// scroll events get fired a LOT
// this will end up being very jerky and distracting if we 
// trigger the animation every time the event fires
// So wait for a split-second before starting the animations,
// resetting the timer on each scroll event to ensure that
// the animation doesn't start until the scrolling has stopped.
var timer = null;
$(window).scroll(function () {
  clearTimeout(timer);
  timer = setTimeout(showDivs, 300);
});

This example does a bit more than what you asked for, in that it animates three separate overlays depending on the scroll position. You can simplify it as-needed for what you need to do – it should be fairly self-explanatory.

Here’s a fiddle if you’d like to see it in action: http://jsfiddle.net/G4t4f/4/

8

solved How to animate a div move horizontally when page is scroll down? [closed]