Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect page scroll to a certain point in jQuery?

Tags:

jquery

Imagine this is my page:

<p>hello</p> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <br /> <p class="myPara">My Paragraph</p> 

How can I alert a message when the user has scrolled down to the paragraph with the class "myPara" and not before then?

like image 508
Jason Avatar asked Feb 18 '11 01:02

Jason


People also ask

How can I determine the direction of jQuery scroll event?

The scrollTop() method in jQuery is used to set or return the vertical scrollbar position for the selected elements. With the hep of this method, we can find the mouse scroll direction. Parameters: This method accepts single parameter position which is optional.

How do I scroll to a specific div?

The scrollTo method: The scrollTo() is used to scroll to the specified element in the browser. Syntax: Here, x-cord specifies the x-coordinate and y-cord specifies the y-coordinate. Example: Using scrollTo() to scroll to an element.

How can check scroll bottom in jQuery?

scroll(function() { if($(window). scrollTop() + window. innerHeight == $(document). height()) { alert("bottom!"); } });


1 Answers

How about:

var target = $(".myPara").offset().top; var interval = setInterval(function() {     if ($(window).scrollTop() >= target) {         alert("made it!");         clearInterval(interval);     } }, 250); 

Here's an example: http://jsfiddle.net/andrewwhitaker/24M3n/1/

You might be tempted to attach an event handler to the window scroll event, but John Resig advises against it (Scroll down to "Best Practices").

Update: As @AbdulJabbarWebBestow points out, it might be a bad idea to unnecessarily run a function every 250ms. Here's an updated example that only runs once, 250ms after the first time a user scrolls:

var target = $(".mypara").offset().top,     timeout = null;  $(window).scroll(function () {     if (!timeout) {         timeout = setTimeout(function () {             console.log('scroll');                         clearTimeout(timeout);             timeout = null;             if ($(window).scrollTop() >= target) {                 alert('made it');             }         }, 250);     } }); 

Example: http://jsfiddle.net/24M3n/858/

like image 66
Andrew Whitaker Avatar answered Oct 21 '22 21:10

Andrew Whitaker