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!
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
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With