October 26, 2024
Chicago 12, Melborne City, USA
jQuery

Javascript/Jquery scroll event to move screen height triggers twice


Creating an autoscroll event to next slide/page of the size of the window. But every time I scroll, the event is triggered twice. I’m guessing because is detecting the autoscroll event as a trigger too and scrolling again. Is there a way to fix it?

        var content = 0;
        var scrolled = 0;
        var contentNum = $('.content').length
        var offset = $("#intro").offset();
        var lastScrollTop = 0;
 
        var timeout;

        $(window).scroll(function() {
            var st = $(this).scrollTop();
            var scrolled = 0;

            clearTimeout(timeout);  
            timeout = setTimeout(function() {
                if (st > lastScrollTop){
                    scrolled = 1;
                } else {
                    scrolled = -1;
                }

                if ( !(content == 0 && scrolled == -1) && !(content == (contentNum-1) && scrolled == +1) ){
                    content = content + scrolled;
                    offset = $(".content").eq(content).offset();

                    $('html').animate({
                        scrollTop: offset.top,
                        scrollLeft: offset.left
                    }, 500);

                }

                lastScrollTop = st;

            }, 50);

            
        });

Tried using global variable, but its still triggering twice.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video