Search code examples
javascriptjqueryhtmlcssanchor-scroll

jQuery - scroll to anchor on button click


Im trying to make a simple script that checks if the user has pressed a button on the webpage. If he does so, it checks if the user has scrolled past a certain div, and if he did, the page scrolls to another else nothing happens.

Technically, my code works since it scrolls the DOM to the anchor but as a side effect, prevents you from scrolling after it did so.

$("#scrollDownBttn").click(function(){

    var mainOffset = $("#pinkRegion").offset().top;

    $(document).on('scroll', function() {
        if ( $(document).scrollTop() > mainOffset ) {
                $(document).scrollTop( $("#brownRegion").offset().top );

        }
        else{

        }

    });
});

Im trying to get used to jQuery, but apparently I still have a long way to go. I cant even figure out why it freezes the whole page. Any ideas why that is the case?


Solution

  • $("#scrollDownBttn").click(function(){
    
        var mainOffset = $("#pinkRegion").offset().top;
    
    
            if ( $(document).scrollTop() > mainOffset ) {
                    $(document).scrollTop( $("#brownRegion").offset().top );
    
            }
            else{
    
            }
    
    
    });
    

    No need to use croll event