screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script> <script src="https://unpkg.com/@babel/standalone@7.14.7/babel.min.js"></script> </head> <body> <div id="app" style="height:10000px"></div> <script type="text/babel"> const { useState, useEffect } = React; function App() { const [visible, setVisible] = useState(false); const toggleVisible = () => { const scrolled = document.documentElement.scrollTop; if (scrolled > 300) { setVisible(true); } else if (scrolled <= 300) { setVisible(false); } }; const scrollToTop = () => { window.scrollTo({ top: 0, behavior: 'smooth' }); }; useEffect(() => { window.addEventListener('scroll', toggleVisible); return () => { window.removeEventListener('scroll', toggleVisible); }; }, []); return ( <> <h3>React Js Scroll to Top of Page</h3> <button className="scroll-to-top-button" onClick={scrollToTop} style={{ display: visible ? 'inline' : 'none' }} > Scroll to top </button> </> ); } ReactDOM.render(<App />, document.getElementById("app")); </script> <style> .scroll-to-top-button { display: none; position: fixed; bottom: 20px; right: 30px; z-index: 99; font-size: 18px; border: none; outline: none; background-color: #555; color: white; cursor: pointer; padding: 15px; border-radius: 4px; } .scroll-to-top-button:hover { background-color: #777; } </style> </body> </html>