32

Is there some way I can fire an event with jQuery when the page scrolls far enough for a div to come into view?

Matty
  • 33,203
  • 13
  • 65
  • 93

5 Answers5

16

If you only need to fire once:

$(window).scroll(function(){
  // This is then function used to detect if the element is scrolled into view
  function elementScrolled(elem)
  {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = $(elem).offset().top;
    return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
  }

  // This is where we use the function to detect if ".box2" is scrolled into view, and when it is add the class ".animated" to the <p> child element
  if(elementScrolled('. box2')) {


  // Your function here

  }
});

Full answer: https://www.thewebtaylor.com/articles/how-to-detect-if-an-element-is-scrolled-into-view-using-jquery

rfornal
  • 5,072
  • 5
  • 30
  • 42
kaelds
  • 317
  • 2
  • 3
  • As an optimization, I think the `elementScrolled` function should be moved out of the scroll callback: 1. There's no need to redefine the function every single frame that the browser window scrolls--hugely wasteful; and 2. It looks like a handy function for other items to use. – whiterook6 Mar 24 '21 at 20:01
14

I think you will have to hook into the scroll event and manually check. Here is a similar question:

Check if element is visible after scrolling

Hope that helps.

Bob

Community
  • 1
  • 1
rcravens
  • 8,320
  • 2
  • 33
  • 26
4

The waypoints plugin covers this and more. http://imakewebthings.com/jquery-waypoints/

Docs: http://imakewebthings.com/jquery-waypoints/#docs

eg:

$('.someSelector').waypoint(function(direction){
//do stuff 
},{
 //bottom-in-view will ensure event is thrown when the element's bottom crosses
 //bottom of viewport.
 offset: 'bottom-in-view'
});
Gokul
  • 2,306
  • 2
  • 17
  • 10
3

A jQuery plugin that adds a bindable 'inview' event for detecting when an element is scrolled into view.

https://github.com/protonet/jquery.inview

Andrew Bucklin
  • 699
  • 8
  • 19
0

if you want to trigger a function when bottom of view, hit top of your content, you can use this function:

$('.ModuleWrapper').waypoint(function (direction) {
    // Codes Here
}, {
    offset: function () {
        return $(this).height();
    }
});

or when bottom of view, hit bottom of your content, you can use this function too:

$('.ModuleWrapper').waypoint(function (direction) {
    // Codes Here
}, {
    offset: function () {
        return -1 * $(this).height();
    }
});

it uses waypoint

Mohamad Shiralizadeh
  • 8,329
  • 6
  • 58
  • 93