E
E
Emil Valeev2015-10-21 15:18:34
css
Emil Valeev, 2015-10-21 15:18:34

How to stop automatic scrolling (jQuery animation) manually?

Task : automatically scroll the page to the end of the block when the user reaches this block manually, but stop the animation if the user starts scrolling manually.

Algorithm : on each scroll, iterate through all the matching elements and compare their coordinates with the current scroll. If the user is within one of these blocks, we start the animation, but if he scrolls manually, we stop

Problem : 1) the animation does not stop 2) Only scrolling with the mouse works, any other one returns to the last elBottom

(Additional) - is it possible to implement a solution simpler than through a loop inside each onscroll? Does the current implementation affect performance in a way that is noticeable?

var $page = $('html, body'),
        arr = document.getElementById('pagesUl').getElementsByClassName('odd');

    window.onscroll = function() {
        var currentScroll = window.pageYOffset || document.documentElement.scrollTop;

        for (var i = 0; i <= arr.length - 1; i++) {
            var elTop = arr[i].getBoundingClientRect().top + pageYOffset,
                elBottom = arr[i].getBoundingClientRect().bottom + pageYOffset;

            if (currentScroll >= elTop && currentScroll < elBottom && i != 2) { 

                $page.animate({
                    scrollTop: elBottom
                }, 2000, 'linear');

                $page.on('mousedown wheel DOMMouseScroll mousewheel keyup touchmove', function() {
                   $page.stop();
                });
                
                return false; 
            };
        };

    };

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Konstantin Gromov, 2015-10-21
@Pathgk

You have a bug in the description of the functionality itself: when a person interrupts the automatic scrolling with his intervention, he will most likely still be inside the current block and the onscroll initiated by the interruption of the animation itself will immediately start a new one. This can be avoided, for example, by removing the block on which the interrupt occurred from the enumeration and returning it there later. But such complications kill the beauty of the functionality itself, and if they are inevitable, it is worth reconsidering the idea itself.
The cycle inside the onscroll is needed in any case, and it takes almost no time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question