3. How to hide cursor using JS

“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

  1. CSS: Use the cursor: none property to hide the cursor.
  2. 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>
    


  3. Functionality

    1. Before Interaction:
      • The cursor is visible.
      • The button reads “Toggle Cursor”.
    2. On Button Click (First Click):
      • The cursor disappears from the entire webpage.
      • The button label changes to “Show Cursor”.
    3. On Button Click (Second Click):
      • The cursor reappears on the webpage.
      • The button label changes back to “Hide Cursor”.
  4. Output

    1. Initial State: The cursor is visible.
    2. On Button Click: The cursor hides, and the button text changes to “Show Cursor”.
    3. On Second Click: The cursor reappears, and the button text changes back to “Hide Cursor”.

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top