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://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> const { useState,useEffect,useRef } = React; function App() { const testRef = useRef(null); const [result, setResult] = useState(''); useEffect(() => { const handleScroll = () => { const itemOffset = testRef.current.offsetTop; const scrollTop = window.scrollY; if (scrollTop >= itemOffset) { setResult('Item has reached the top'); } else { setResult(''); } }; window.addEventListener('scroll', handleScroll); return () => { window.removeEventListener('scroll', handleScroll); }; }, []); return ( <div className='container' style={{ height: '600px' }}> <div ref={testRef}> React JS Dynamically check if elements hit top of window </div> {result && <small className="result">{result}</small>} </div> ); } ReactDOM.render(<App />, document.getElementById('app')); </script> <style> .container { max-width: 800px; margin: 0 auto; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); text-align: center; } .result { font-size: 16px; color: #4CAF50; /* Green */ position: fixed; left: 50%; transform: translateX(-50%); bottom: 20px; background-color: #333; color: #fff; padding: 12px; border-radius: 6px; z-index: 9999; transition: opacity 0.3s ease-in-out; } </style> </body> </html>