How can I determine how the scrollbar scrolls in javascript?

I have the following jquery to handle scroll events on a specific div and write some content:

$('#myDiv').scroll(function(eventData) { if(eventData.isGoingUp) $('#myDiv').prepend('<p>Going up.</p>'); else $('#myDiv').append('<p>Going down.</p>'); }); 

Obviously evt.isGoingUp does not actually exist. Is there something that can fulfill this logic?

+6
jquery event-handling scroll
source share
2 answers

I hope this solution is useful to you ... it will work on all elements with the class name 'scroll-track'. You must also provide a new attribute to the scrollable element: data-scroll = '{"x": "0", "y": "0"}' You can check it here: http://jsfiddle.net/CgZDD/

-js -

 $(document).ready(function(){ // make sure overflow is set to 'scroll' $('.scroll-track').css({ overflow: 'scroll' }); $('.scroll-track').scroll(function() { var scrollData = $(this).data('scroll'); if(scrollData.y > $(this).scrollTop()){ $('#scrollDir').append($(this).attr('id') + ' up'); }else if(scrollData.y != $(this).scrollTop()){ $('#scrollDir').append($(this).attr('id') + ' down'); } if(scrollData.x > $(this).scrollLeft()){ $('#scrollDir').append($(this).attr('id') + ' left'); }else if(scrollData.x != $(this).scrollLeft()){ $('#scrollDir').append($(this).attr('id') + ' right'); } $('#scrollDir').append('<br />'); scrollData.x = $(this).scrollLeft(); scrollData.y = $(this).scrollTop(); $(this).data('scroll', scrollData); }); }); 
+4
source share

You can save the previous scroll value and check if the value has increased or decreased:

 var prev = $('#myDiv').scrollTop(); $('#myDiv').scroll(function(eventData) { var cur = $(this).scrollTop(); if (cur > prev) { // scrolled down } else { // scrolled up } prev = cur; }); 
+2
source share

All Articles