“How to hide cursor using JS”
Introduction
This task demonstrates how to hide the cursor on a webpage using JavaScript and CSS. Hiding the cursor is a feature commonly used in specific web applications, such as custom video players, interactive experiences, or games, where the cursor may interfere with the UI.
Implementation Details
- CSS: Use the
cursor: none
property to hide the cursor. - JavaScript:Dynamically apply or remove the CSS style for flexibility. This allows toggling the visibility of the cursor.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hide Cursor Using JavaScript</title> <style> /* Default body cursor */ body.hide-cursor { cursor: none; } </style> </head> <body> <h2>Hide Cursor Using JavaScript</h2> <p>Click the button below to hide or show the cursor:</p> <button id="toggle-cursor-btn">Toggle Cursor</button> <script> const button = document.getElementById('toggle-cursor-btn'); const body = document.body; // Toggle cursor visibility button.addEventListener('click', () => { body.classList.toggle('hide-cursor'); const isHidden = body.classList.contains('hide-cursor'); button.textContent = isHidden ? "Show Cursor" : "Hide Cursor"; }); </script> </body> </html>
-
Functionality
- Before Interaction:
- The cursor is visible.
- The button reads “Toggle Cursor”.
- On Button Click (First Click):
- The cursor disappears from the entire webpage.
- The button label changes to “Show Cursor”.
- On Button Click (Second Click):
- The cursor reappears on the webpage.
- The button label changes back to “Hide Cursor”.
- Before Interaction:
-
Output
- Initial State: The cursor is visible.
- On Button Click: The cursor hides, and the button text changes to “Show Cursor”.
- On Second Click: The cursor reappears, and the button text changes back to “Hide Cursor”.