0

I want to be able to turn on $(document).on('scroll', function() {...}); when I turn it off using $(document).off('scroll');

My code so far I tried using debounce function, but I am getting

Illegal invocation

function scroller(lang, type, genre, sort, page) {
    console.log($(this).scrollTop() * 2, $('#pages').position().top);
    if ($(this).scrollTop() * 2 >= $('#pages').position().top) {
        $.post('<?= (new UrlLibry)->SetUrl('bookshop', 'jajax', 'page'); ?>', {lang: lang, type: type, genre: genre, sort: sort, pages: page}, function(data) {
            $('#loadmore').append(data);
            page++;
            $('#pageNumber').data('page', page);
        });
    }
}

var debouncedMouseMove = debounce(scroller, 50);
$(document).on('scroll', debouncedMouseMove);
Dimitar
  • 1,830
  • 5
  • 32
  • 52

1 Answers1

1

You may decouple the handler function from the .on() call.

Moreover, if you substitute everything with a debounce function you need to continue to consider the function must have only one argument: event.

I used debounce function contained into underscorejs library.

function scroller(event) {
  console.log('called...');
  return;

    var lang, type, genre, sort, page; // cannot pass as argument
    console.log($(this).scrollTop() * 2, $('#pages').position().top);
    if ($(this).scrollTop() * 2 >= $('#pages').position().top) {
        $.post("<?= (new UrlLibry)->SetUrl('bookshop', 'jajax', 'page'); ?>",
                {lang: lang, type: type, genre: genre, sort: sort, pages: page}, function(data) {
            $('#loadmore').append(data);
            page++;
            $('#pageNumber').data('page', page);
        });
    }
}

var debouncedMouseMove = _.debounce(scroller, 50);
$(document).on('scroll', debouncedMouseMove);
body {
    height: 400vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
  • i think it is working with debounce function, but now i am getting `Illegal invocation` – Dimitar Jun 19 '19 at 18:05
  • thank you very much, i manage to do it without the underscore lib, do i need it? I mean i prefer not to use external libraries if i can because i tent to want my performance of the loading time for my website to be less then 2 seconds. – Dimitar Jun 20 '19 at 06:11