1

I need to detect scroll direction on mouseenter on certain div so I try to use code below

$.fn.scroll = function () {
var $this = $(this);
var $list = $(this).find('ul');
var $lis = $list.find('li');
var direction;

$this.addClass('scroll');
$list.addClass('slides-list');
$lis.addClass('slide');
$lis.filter(':first').addClass('current');
$lis.filter(':not(:first)').addClass('past');

$this.on('mouseenter', function(){

    var lastScrollTop = $this.offset().top;

    $(window).scroll(function () {
        if ($this.hasClass('animated')) {
            return;
        }

        var scrollTop = $(window).scrollTop();

        if (scrollTop > lastScrollTop) {
            direction = 'down';
        } else {
            direction = 'up';
        }

        lastScrollTop = scrollTop;
    });

});
}

$(document).ready(function () {
    $('#scroll').scroll();
});

but in line
var lastScrollTop = $this.offset().top;
I get an error
Uncaught TypeError: Cannot read property 'top' of undefined.

I guess I have some problem with scopes, but I don't know how to fix it?

truslivii.lev
  • 701
  • 1
  • 8
  • 21

3 Answers3

0

Try with this readonly property:

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop

And check this question as well

offsetTop vs. jQuery.offset().top

Community
  • 1
  • 1
ChesuCR
  • 9,352
  • 5
  • 51
  • 114
0

Try this

$('#scroll').bind('mousewheel', function(event) {
if (event.originalEvent.wheelDelta >= 0) {
    console.log('Scroll up');
}else {
    console.log('Scroll down');
}});

More on How can I determine the direction of a jQuery scroll event?

Community
  • 1
  • 1
Dusan Krstic
  • 663
  • 10
  • 17
0

Try replacing $this with $(this) or $("#scroll") it works

Cijo V J
  • 261
  • 1
  • 3
  • 14