Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if div is viewable in window?

I have a one page site with fixed navigation and using a scroll script, very similar to this: http://www.ivanjevremovic.in.rs/live/temptation/single/orange/index-cycle-slider.html

What I'm looking for is a way to check what section is viewable in the window to set the active state on the nav when using the browsers scroll bar, any ideas?

like image 576
Ashley Graham Avatar asked Nov 13 '11 20:11

Ashley Graham


People also ask

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

If an element is in the viewport, it's position from the top and left will always be greater than or equal to 0 . It's distance from the right will be less than or equal to the total width of the viewport, and it's distance from the bottom will be less than or equal to the height of the viewport.

Is element visible on screen JavaScript?

To know whether the element is fully visible in viewport, you will need to check whether top >= 0, and bottom is less than the screen height. In a similar way you can also check for partial visibility, top is less than screen height and bottom >= 0. The Javascript code could be written as : window.

Is element in viewport jQuery?

Check if element is visible in viewport using jquery:If the bottom position of the viewport is greater than the element's top position AND the top position of the viewport is less than the element's bottom position, the element is in the viewport (at least partially).


1 Answers

Here are all the variables you'll need...

var $myElt       = $('.myElement');      // whatever element you want to check
var $window      = $(window);            // the window jQuery element
var myTop        = $myElt.offset().top;  // the top (y) location of your element
var windowTop    = $window.scrollTop();           // the top of the window
var windowBottom = windowTop + $window.height();  // the bottom of the window

Then to make sure your element is within the window's range...

if (myTop > windowTop && myTop < windowBottom) {
    // element is in the window
} else {
    // element is NOT in the window
    // maybe use this to scroll... 
    // $('html, body').animate({scrollTop: myTop}, 300);
}

jQuery reference:

  • http://api.jquery.com/offset/
  • http://api.jquery.com/height/
  • http://api.jquery.com/scrollTop/
like image 199
Luke Avatar answered Sep 27 '22 18:09

Luke