简体   繁体   中英

JavaScript getting stuck in a loop?

I am trying to perform a simple animation that I would like to happen after a successful return of an AJAX call.

$('#result').click(function(){
    $(document).ajaxSuccess(function(){
    $('html, body').on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function(){
        $('html, body').stop();
    });
    $('html, body').animate({
        scrollTop: $('#result').position().top
    }, 500, function(){
        $('html, body').off("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove");
    });

    });
});

The problem is that sometimes, not always, the animation does not seem to want to exit in that it causes jerky movements and a constant return to the top of the div if the user attempts to scroll away. When I remove the ajaxSuccess requirement, the problem does not occur. Any ideas?

There is no need to stop mousewheel, scroll etc. movement by using stop() function.

animate function won't be disturbed until it has reached the document top.

This would do:

$('#result').click(function(){
    $(document).ajaxSuccess(function(){
        $('html, body').animate({
            scrollTop: $('#result').position().top
        }, 500);
    });
});

You're attaching a new ajaxSuccess callback every time the user clicks on #result .

This means that if the user clicked on #result N times, then N different functions are attached to be executed whenever an ajax request completes successfully. And each function will try to animate $('html, body')

Solution: Move your code out of $('#result').click function or unbind previous handlers before binding a new one.

And here is the simplified example of what is happening. Try to click two buttons one after another:

 $("#one").click(() => { console.log("Clicked First") $("#two").click(() => console.log("Clicked Second")); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id=one>First</button> <button id=two>Second</button> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM