Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can jQuery determine which divs are currently in the user's browser view?

Is it possible to determine which div is currently in the browser's view, and then fire an event when that occurs? Basically, I have a website that has 5-6 sections all on one page and I want to fire events depending on which section is currently in view on the browser. I know we can link directly to positions of a page using the # tag in hrefs, but is this possible to determine which is currently in main view on the browser?

like image 978
mcriecken Avatar asked Feb 12 '12 19:02

mcriecken


1 Answers

Yes, you can do that. The basic idea behind that is to watch the scrolling and to determine which of your sections is focused by the user. A good guess for this is usually the section, which is next to the top of your viewport:

$(document).scroll(function() {
  var $this = $(this),
      scrollTop = $this.scrollTop(),
      // find the section next to the current scroll top
      sections = $(this).find('section'),
      topSection = null,
      minDist = Infinity;

  sections.each(function() {
    // calculate top and bottom offset of the section
    var top = $(this).offset().top,
        bottom = top + $(this).innerHeight(),
        // only use the minimum distance to the scroll top
        relativeDistance = Math.min(
          Math.abs(top - scrollTop), 
          Math.abs(bottom - scrollTop)
        );
    // in case the distance is smaller than
    // the previous one's replace it
    if (relativeDistance < minDist) {
      minDist = relativeDistance;
      topSection = this;
    }
  });

  // flip the 'top' class from current to now next one
  $('section.top').removeClass('top');
  $(topSection).addClass('top');    
});

You can see a quite nice example of this at the Play Webframework's Homepage

If that is not quite what you want, you may observe the full offset or position of any Element and compare it to the current viewport using $(window).innerWidth() or $(window).innerHeight()

UPDATE Added a jsbin to see it in action. Enjoy ;)

like image 66
Tharabas Avatar answered Sep 27 '22 17:09

Tharabas