I'm looking for something to this effect:
$(window).scroll(function(event){ if (/* magic code*/ ){ // upscroll code } else { // downscroll code } });
Any ideas?
To get or set the scroll position of an element, you follow these steps: First, select the element using the selecting methods such as querySelector() . Second, access the scroll position of the element via the scrollLeft and scrollTop properties.
The scrollLeft() method sets or returns the horizontal scrollbar position for the selected elements. Tip: When the scrollbar is on the far left side, the position is 0. When used to return the position: This method returns the horizontal position of the scrollbar for the FIRST matched element.
Pressing page up scrolls up one page or gets you to the top of the page. Pressing page down scrolls down one page at a time or gets you to the bottom of the page. Some people may also refer to the page up and page down keys as the scroll keys, not to be confused with the scroll lock key.
jQuery scrollTop() Method The scrollTop() method sets or returns the vertical scrollbar position for the selected elements.
Check current scrollTop
vs previous scrollTop
var lastScrollTop = 0; $(window).scroll(function(event){ var st = $(this).scrollTop(); if (st > lastScrollTop){ // downscroll code } else { // upscroll code } lastScrollTop = st; });
You can do it without having to keep track of the previous scroll top, as all the other examples require:
$(window).bind('mousewheel', function(event) { if (event.originalEvent.wheelDelta >= 0) { console.log('Scroll up'); } else { console.log('Scroll down'); } });
I am not an expert on this so feel free to research it further, but it appears that when you use $(element).scroll
, the event being listened for is a 'scroll' event.
But if you specifically listen for a mousewheel
event by using bind, the originalEvent
attribute of the event parameter to your callback contains different information. Part of that information is wheelDelta
. If it's positive, you moved the mousewheel up. If it's negative, you moved the mousewheel down.
My guess is that mousewheel
events will fire when the mouse wheel turns, even if the page does not scroll; a case in which 'scroll' events probably are not fired. If you want, you can call event.preventDefault()
at the bottom of your callback to prevent the page from scrolling, and so that you can use the mousewheel event for something other than a page scroll, like some type of zoom functionality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With