Clicking outside textarea makes cursor appear outside of textarea

43 Views Asked by At

I've noticed this behavior for textarea where clicking outside of it, either to the right or left makes a cursor appear outside the text area. Is there anyway to hide the cursor when clicking outside the text area, but keep it inside of it.

Codepen:https://codepen.io/chris123312/pen/GReGBWZ

Example of the blinking cursor showing outside of the textarea

I can't seem to find anything about this online and chatgpt has provided JS solutions that simply don't work:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Textarea with Hidden Cursor Outside</title>
        <style>
            /* Add your custom styles here */
            .hide-cursor-outside {
                border-radius: 10px; /* Adjust the border radius as needed */
                padding: 10px; /* Optional: Add padding for better visual appearance */
                width: 300px; /* Optional: Set a specific width */
                height: 150px; /* Optional: Set a specific height */
                cursor: text; /* Show the cursor inside the textarea */
            }
            .hide-cursor-outside:focus {
                cursor: default; /* Hide the cursor outside the textarea when focused */
            }
        </style>
    </head>
    <body>
    
        <textarea class="hide-cursor-outside" placeholder="Type something here..."></textarea>
    
        <script>
            // Add event listeners to dynamically toggle the class
            const textarea = document.querySelector('.hide-cursor-outside');
            
            textarea.addEventListener('focus', () => {
                textarea.classList.add('hide-cursor-outside');
            });
    
            textarea.addEventListener('blur', () => {
                textarea.classList.remove('hide-cursor-outside');
            });
        </script>
    
    </body>
    </html>

3

There are 3 best solutions below

1
Bob Doe On BEST ANSWER
0
Ali Ismaeel On

I didn't fully understood what do you mean but anyway, there is a CSS property for the cursor , you can find it here

you can define a CSS class for the area where you want the cursor to be hidden like this

.no_cursor {cursor: none;}
0
mr.Penguin On

I'm not sure I understood your question, but here's a workaround to focus the mouse on the textarea whenever the user clicks outside:

<body>

    <textarea id="textarea" placeholder="Type something here..."></textarea>


<script>
document.body.addEventListener('click', function(event) {
  var textarea = document.getElementById('textarea');
  if (!textarea.contains(event.target)) {
    textarea.focus();
  }
});
</script>

</body>