Voidvalkon
Voidvalkon

Reputation: 46

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?

Upvotes: 2

Views: 6725

Answers (2)

paranjothi
paranjothi

Reputation: 113

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

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


        if ( $(document).scrollTop() > mainOffset ) {
                $(document).scrollTop( $("#brownRegion").offset().top );

        }
        else{

        }


});

No need to use croll event

Upvotes: 1

SrAxi
SrAxi

Reputation: 20005

Try this:

$("#scrollDownBttn").click(function(){            
    $('html, body').animate({
            scrollTop: $("#pinkRegion").offset().top
        }, 500);
});

Upvotes: 2

Related Questions