I have a simple problem, but I can't find the solution ... I just want to launch an event (which execute a method) when I scroll my page up and I "touch" the top of it. I'm using JavaScript and jQuery in my page. Thanks in advance !
I have a simple problem, but I can't find the solution ... I just want to launch an event (which execute a method) when I scroll my page up and I "touch" the top of it. I'm using JavaScript and jQuery in my page. Thanks in advance !
Share Improve this question asked Feb 27, 2013 at 21:47 DaveLeGODaveLeGO 871 silver badge9 bronze badges 5 |3 Answers
Reset to default 9You should use the scroll event for that purpose:
$(window).scroll(function() {
if ($(this).scrollTop() == 0) {
//Do whatever you want to do
}
});
One thing you should notice is that this way when somebody scrolls to top continuously the even will be fired although you only want it once the top is hit, for this you can define the event handler as a function and put the last scrolltop value into a function local variable.
$(window).scroll(handleHitTop);
function handleHitTop(event) {
var currentScrollTopValue = $(this).scrollTop();
if (handleHitTop.lastTop === undefined) {
handleHitTop.lastTop = currentScrollTopValue ;
return;
}
if (handleHitTop.lastTop == 0 && currentScrollTopValue == 0) {
return;
}
handleHitTop.lastTop = currentScrollTopValue;
if (handleHitTop.lastTop == 0) {
//Call your event here
}
}
Use the onscroll event. Vanilla js example:
window.onscroll = function() {
if(document.body.scrollTop == 0) {
alert('yay!');
}
}
http://jsfiddle.net/kuWuf/
Use a .scroll()
handler and .scrollTop()
:
$(window).scroll( function() {
if($(this).scrollTop() == 0) {
alert("Top!!!");
}
});
http://jsfiddle.net/jtbowden/wvJ9r/
body.on.scroll = function() { if (window.is.top || document.above.fold && google.search.is.not.done() || I put(no.effort.into.this) ) alert('I'll do more research!'); }
– adeneo Commented Feb 27, 2013 at 22:05