I'm trying to figure how to trigger an jquery animation when the user scrolls to the middle of the page. Is there a way to set a listener to see if the person scrolls halfway down the page it activates the jquery code?
-
1That will vastly depend on page height and client resolution. I'd go for a solution which checks if an element or certain point in the document is in the user's viewpoint. – Fabrício Matté Jul 29 '12 at 03:40
-
duplication : http://stackoverflow.com/a/5036892/889678 – mgraph Jul 29 '12 at 03:46
-
twitter bootstrap has a cool jquery plugin. check it out – Ryan Jul 29 '12 at 03:46
-
possible duplicate of [How to detect page scroll to a certain point in jQuery?](http://stackoverflow.com/questions/5036850/how-to-detect-page-scroll-to-a-certain-point-in-jquery) – Dan F Jul 29 '12 at 03:48
-
@DanF sorry about that, I couldn't find it anywhere in the search, I guess I didn't word correctly. – Frank Aguilar Jul 29 '12 at 03:52
3 Answers
Using jQuery, you can attach an event handler to the scroll event, which will let you listen to whenever the window is scrolled and determine whether the user has scrolled the appropriate amount.
$(window).scroll(function () {
if (($(window).scrollTop()) > ($(document).height() / 2)) {
// Run animation here
}
});

- 13,035
- 3
- 50
- 67
-
You're testing for half of the `window` (user's viewpoint), not the `document` (page) though. – Fabrício Matté Jul 29 '12 at 04:21
-
Illustrating what I said: [fiddle](http://jsfiddle.net/ult_combo/XdqPJ/1/). Should be closer to OP's request. – Fabrício Matté Jul 29 '12 at 04:23
Think so.. you can look at checking parts of the page using; setInterval(name_Of_Function,1000);
runs every second, then run a check on there is; window.pageYOffset // Gives you current horizontal window scroll position for the page.
Firebug is helpful to get more information on these functions. Remember to check in all major browsers as the implementation or values returned may be slightly different between different browsers.
Good reference page I found; http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html

- 484
- 2
- 8
Is there a way to set a listener to see if the person scrolls halfway down the page it activates the jquery code?
You can get the amount that the user has scrolled with the following:
$("html,body").scrollTop();
so, to trigger an event halfway down the page:
if (($("html,body").scrollTop()) > ($("html,body").height() / 2))
{
// Code that will be triggered
}
You would need a timer to constantly be checking this. You can use setInterval()
in Javascript to repeatedly execute a function to check this.

- 37,233
- 13
- 109
- 109