write a javascript function that scrolls to the top of a webpage when a button is clicked
- User
write a javascript function that scrolls to the top of a webpage when a button is clicked
- Assistant
Here's an example code that uses JavaScript to scroll to the top of the page when a button is clicked:
javascriptfunction scrollToTop() { document.body.scrollTop = 0; // For Safari document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE, and Opera } // Attach the function to a button element with an id of "scrollBtn" var scrollBtn = document.getElementById("scrollBtn"); scrollBtn.addEventListener("click", scrollToTop);When the
scrollToTop()function is called, it sets thescrollTopproperty of both thedocument.bodyand thedocument.documentElementto0, which will effectively scroll the page to the top.To trigger the
scrollToTop()function when the button is clicked, we first need to select the button element usingdocument.getElementById(). In this example, we're assuming that the button has an id of "scrollBtn". We then attach an event listener to the button using to listen for the "click" event. When the button is clicked, it will call the function and scroll the page to the top. - User
write some code for a button on a webpage, in css3, javascript and html5. the button is hidden until the user scrolls down 20 pixels, the button then smoothly fades into view. when the button is clicked, it executes a javascript function that scrolls to the top of the page
- Assistant