Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I tell which way a scrolling pane is scrolling in javascript?

I have the following jquery to handle scroll events on a particular 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 doesn't actually exist. Is there anything that does exist that can accomplish this logic?

like image 367
Ax. Avatar asked Nov 29 '10 20:11

Ax.


2 Answers

Hopefully this solution is useful for you... it will work on all elements with class name 'scroll-track'. You must also provide a new attribute to the scrollable element: data-scroll='{"x":"0", "y":"0"}' You can test 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);
    });
});
like image 147
Nick G Avatar answered Sep 27 '22 23:09

Nick G


You could store the previous scroll value and check whether 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;
});
like image 32
casablanca Avatar answered Sep 28 '22 00:09

casablanca