Kyle Yeo
Kyle Yeo

Reputation: 2368

Animate divs according to browser height

I want to animate a certain div in the DOM when the user scrolls to a certain height on the webpage, such as 600px.

Problem is, I'm looking through Google and I can't find anything about it -- it's all about easing.

Can anyone help me with this? I'm looking at jQuery and Javascript documentations but still no dice.

Upvotes: 1

Views: 94

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337580

Try this:

var timer;

$(document).scroll(function() {
    clearTimeout(timer);
    timer = setTimeout(function() {
        if ($(document).scrollTop() > 600) {
            $("#myDiv").animate({ height: "100px" });
            $("#myOtherDiv").animate({ width: "225px" });
        }

        if ($(document).scrollTop() > 700) {
            $("#anotherDiv").animate({ height: "300px" });
        }
    }, 100);
});

Note the timer here is important otherwise you could end up with literally thousands of scroll events being needlessly handled. The timer ensures the function runs once scrolling has ended.

Upvotes: 2

Nic
Nic

Reputation: 581

You can use the scroll event (see: jQuery API - scroll()) to detect scrolling and use the value of scrollTop() (see: jQUery API - scrollTop()) to check how far the user has scrolled to trigger further action.

Upvotes: 1

Related Questions