Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Lose input hints (get focus) after pressing mouse cursor in a textbox with JavaScript
In this tutorial, we'll learn how to clear placeholder-like text from an input field when the user clicks on it (gets focus) and restore it when the field loses focus if no text was entered.
Let's say we have the following input field with hint text:
<label for="name">StudentName:<input name="name" id="studentName" value="Enter your Name ????" class="guess"></label>
To lose input hints on pressing mouse cursor, we use the onfocus and onblur events.
How It Works
The solution uses two JavaScript functions:
- onfocus: Clears the hint text when user clicks in the field
- onblur: Restores hint text if the field is empty when user clicks away
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Input Hints Example</title>
</head>
<body>
<label for="name">StudentName:
<input name="name" id="studentName" value="Enter your Name ????" class="guess">
</label>
<script>
function guessFocus() {
if (this.value == this.defaultValue)
this.value = '';
}
function guessBlur() {
if (this.value == '')
this.value = this.defaultValue;
}
var inputElement = document.getElementById('studentName');
inputElement.onfocus = guessFocus;
inputElement.onblur = guessBlur;
</script>
</body>
</html>
Code Explanation
The guessFocus() function checks if the current value matches the default value (hint text). If so, it clears the field. The guessBlur() function restores the hint text if the field is empty when focus is lost.
Modern Alternative with Placeholder
For modern browsers, you can use the HTML5 placeholder attribute which provides this functionality automatically:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Placeholder Example</title>
</head>
<body>
<label for="name">StudentName:
<input name="name" id="studentName" placeholder="Enter your Name ????">
</label>
</body>
</html>
Comparison
| Method | Browser Support | JavaScript Required | Flexibility |
|---|---|---|---|
| onfocus/onblur | All browsers | Yes | High - custom behavior |
| placeholder attribute | Modern browsers | No | Limited - built-in behavior |
Conclusion
The onfocus/onblur approach provides backward compatibility and custom control over hint behavior. For modern applications, the HTML5 placeholder attribute offers a simpler, native solution.
