noobski
noobski

Reputation: 3

Scrolling after reaching a certain position using javascript

Little disclaimer: I'm not a native english speaker. My page contains of 3 basic blocks, each of them is a size of a window. Header, an article and footer. I know that i shouldn't mess with the way page is controlled by the user but i have that idea where after reaching a certain point on page the view scrolls down/up showing the whole block/div. So far "prototype" looks like this:

            var yOffset = window.pageYOffset;
            var header = document.getElementById('header');
            var headerHeight = $("#header").height();

            if(yOffset >= headerHeight2){
                $("body,html").animate(
                    {
                        scrollTop : 500                       
                    }, 400); 
            }

My biggest problem with it it's that it only works when i srcoll down and reload my page.

Upvotes: 0

Views: 661

Answers (3)

Eivind
Eivind

Reputation: 841

Look into Waypoint http://imakewebthings.com/waypoints/ and use the offset option to control when the function should be invoked. http://imakewebthings.com/waypoints/api/offset-option/

This gives you very good control of how and when to trigger actions when user scrolls the page.

Upvotes: 0

Emil B
Emil B

Reputation: 41

The way you are describing it, it seems as if your code is run right when the page is loaded. What you need to do here is find a way to run your scroll code when you reach a certain point.

Since you seem to be using jquery I will try to give you an example of how this can be accomplished:

// we can fetch the header and store it into a variable right away
// so that we don't fetch it on every scroll action.
var header = document.getElementById('header');
var headerHeight = $("#header").height();
var yOffset = window.pageYOffset;

// This is fetched here to minimize the amount of
// jquery searches we do inside the 'onScroll'-function
// since it is being called multiple times
var elementToAnimate = $("body,html");

// Here we tell jquery that we want to run this function
// every time the window is scrolled.
$(window).scroll(function() {
    // Here I just pasted your code since you said it worked.
    yOffset = window.pageYOffset;

    if(yOffset >= headerHeight2){
        elementToAnimate.animate(
            {
                scrollTop : 500                       
            }, 400); 
    }
});

I haven't had the time to try this, but from your description it seems as if it should work. Please comment if it doesn't and I'll fix it.

Please ask if I didn't explain it well enough :)

Upvotes: 2

Mathew
Mathew

Reputation: 89

As you're using jquery you can use $(window).scroll() event to get actual scroll, than compare it to headerHight like so:

$(window).scroll(function(){
var yOffset = $(window).scrollTop()
if(yOffset >= headerHeight2){
}
})

You got the idea

Upvotes: 0

Related Questions