Javascript – How to scroll to top when a button is clicked

javascriptjquery

I have a button on a page and I want that when it is clicked, the page scrolls to the 0 position.

HTML

<button id="button">Back to top </button>

jquery

$(document).scroll(function(){

        var scroll_pos = $(window).scrollTop()
    if(scroll_pos > 10){

        $('#button').click(function(){

        // what code to enter here??


        });

    }
    });

Best Solution

Try this code:

$("#button").on("click", function() {
    $("body").scrollTop(0);
});

Method on binds a click event to the button and scrollTop scrolls your body to 0 position.

Related Question