How Can I Launch A Javascript Or Jquery Event When I Reach The Top Of My Page?
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 J
Solution 1:
You 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);
functionhandleHitTop(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
}
}
Solution 2:
Use the onscroll event. Vanilla js example:
window.onscroll = function() {
if(document.body.scrollTop == 0) {
alert('yay!');
}
}
Solution 3:
Use a .scroll()
handler and .scrollTop()
:
$(window).scroll( function() {
if($(this).scrollTop() == 0) {
alert("Top!!!");
}
});
Post a Comment for "How Can I Launch A Javascript Or Jquery Event When I Reach The Top Of My Page?"