Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to top when a button is clicked?

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??


        });

    }
    });
like image 719
Ronny K Avatar asked May 05 '12 10:05

Ronny K


People also ask

How do I scroll to the top when I click the button?

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

How do you scroll to top on a button click in React?

If you need to scroll to the top of the page when a button is clicked, set the onClick prop on the element, passing it a function. The function should call the window. scrollTo() method just like we did in the useEffect hook.

How do you quickly scroll to the top of a page?

Scroll one page at a time in all major browsers including Microsoft Internet Explorer and Mozilla Firefox by pressing the Spacebar key. Move back up the page by pressing Shift + Spacebar or the Home key on the keyboard.

How do you use the scroll top function?

Definition and UsageThe scrollTop() method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0. When used to return the position: This method returns the vertical position of the scrollbar for the FIRST matched element.


1 Answers

you can use window function for scrollTop jquery

 $("#button").click( function() {
   $(window).scrollTop(0);
 });

When you click button, this page scroll to top of the position.

like image 113
Selvamani Avatar answered Oct 08 '22 06:10

Selvamani