I want to run a function when someone scrolls down on an element. Something like this:
$('div').scrollDown(function(){ alert('down') }); $('div').scrollUp(function(){ alert('up') });
But those functions don't exist. Is there a solution to this problem? Awwwards seem to be able to do it (logo in navbar changes depending on scroll direction). Unfortunately, the source code is compressed, so no luck there.
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.
Listen to the scroll Event to set a scroll event listener to the window. onscroll property. Then we get the scrollY value and check if it's bigger than the oldScroll value. If it's bigger, that means we're scrolling down.
To get the current scroll position of ScrollView in React Native, we can set the onScroll prop of the ScrollView to a function that takes the scroll event object as an argument.
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.
I managed to figure it out in the end, so if anyone is looking for the answer:
//Firefox $('#elem').bind('DOMMouseScroll', function(e){ if(e.originalEvent.detail > 0) { //scroll down console.log('Down'); }else { //scroll up console.log('Up'); } //prevent page fom scrolling return false; }); //IE, Opera, Safari $('#elem').bind('mousewheel', function(e){ if(e.originalEvent.wheelDelta < 0) { //scroll down console.log('Down'); }else { //scroll up console.log('Up'); } //prevent page fom scrolling return false; });
Following example will listen to MOUSE scroll only, no touch nor trackpad scrolls.
It uses jQuery.on() (As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document).
$('#elem').on( 'DOMMouseScroll mousewheel', function ( event ) { if( event.originalEvent.detail > 0 || event.originalEvent.wheelDelta < 0 ) { //alternative options for wheelData: wheelDeltaX & wheelDeltaY //scroll down console.log('Down'); } else { //scroll up console.log('Up'); } //prevent page fom scrolling return false; });
Works on all browsers.
fiddle: http://jsfiddle.net/honk1/gWnNv/7/
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