views:

2137

answers:

2

I am trying to change the text inside a div based on how far down a page you have scrolled. I've been tinkering with jQuery's scrollTop and document height but have so far failed to produce the desired results.

How would I get the position of an element on the page and then get jQuery to do something once you have scrolled to that elements position?

Help is much appreciated!

+4  A: 

There was a question on Stackoverflow that asked something similar and I whipped up a small example to illustrate how to accomplish this. I can't find the question right now, but here is the example. In this example there is a div that is shown until you scroll to a certain element in the page at which point the div is hidden. You can change this to achieve what you want, as the idea is the same. Here is the code modified for what you need:

$(document).ready(function() {
    function isScrolledIntoView(elem) {
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();

        var elemTop = $(elem).offset().top;
        var elemBottom = elemTop + $(elem).height();

        return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
    }

    var myelement = $('#formcontainer'); // the element to act on if viewable
    $(window).scroll(function() {
        if(isScrolledIntoView(myelement)) {
            // do something when element is scrolled to and viewable
        } else {
            // do something when element is not viewable
        }
    });
});
Paolo Bergantino
Ah this is exactly what I was trying to do. Thanks!
Cawlin
A: 

Good old ppk from quirksmode.org can show you how to find the position of an element: "This script finds the real position, so if you resize the page and run the script again, it points to the correct new position of the element."

cofiem