Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change div based on how far down the page you have scrolled

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!

like image 425
Cawlin Avatar asked Dec 31 '22 04:12

Cawlin


1 Answers

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
        }
    });
});
like image 92
Paolo Bergantino Avatar answered Jan 01 '23 17:01

Paolo Bergantino