Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test in JQuery if an element is at the top of screen

Tags:

jquery

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?

like image 732
sir_thursday Avatar asked Sep 25 '11 04:09

sir_thursday


People also ask

How do you check if an element is at 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.

How do I check if a div is at the top of the page?

scroll(function() { if ( $window. scrollTop() >= distance ) { // Your div has reached the top } });

How do you check if an element is in the viewport?

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.

Is element visible on screen jQuery?

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.


1 Answers

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.

like image 105
Joseph Silber Avatar answered Oct 02 '22 11:10

Joseph Silber