Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: How can I trigger an event when a div comes into view? [duplicate]

Tags:

jquery

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

like image 375
Matty Avatar asked Jan 29 '11 15:01

Matty


4 Answers

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

like image 176
kaelds Avatar answered Oct 05 '22 06:10

kaelds


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

like image 35
rcravens Avatar answered Oct 05 '22 06:10

rcravens


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'
});
like image 20
Gokul Avatar answered Oct 05 '22 06:10

Gokul


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

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

like image 37
Andrew Bucklin Avatar answered Oct 05 '22 07:10

Andrew Bucklin