I have a div
that is positioned about 100px from the top of the browser window. When the user scrolls down, I want the div
to stay where it is until it reaches the top of the screen. Then, I'll change some CSS with JQuery to make the position to change to fixed and the margin-top to 0. How can I test in JQuery if this div
is at the top of the screen?
Thanks! You can use the offset() method to obtain where an element is relative to the document, and you can use the scrollTop() method to figure out where the top of the document is. If the element offset is at 1000 and scrollTop is more than 1000, you know that you've scrolled the element above off the screen.
scroll(function() { if ( $window. scrollTop() >= distance ) { // Your div has reached the top } });
Summary. Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport. Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.
Answer: Use the jQuery :visible Selector You can use the jQuery :visible selector to check whether an element is visible in the layout or not. This selector will also select the elements with visibility: hidden; or opacity: 0; , because they preserve space in the layout even they are not visible to the eye.
var distance = $('div').offset().top, $window = $(window); $window.scroll(function() { if ( $window.scrollTop() >= distance ) { // Your div has reached the top } });
P.S. For better performance, you should probably throttle the scroll event handler.
Check out John Resig's article: Learning from Twitter.
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