JavaScript Focus Event on a Text Box

Table of Contents
Text input focus example

The focus event fires when a form control receives focus, whether by mouse, touch, keyboard navigation, or script. The original example uses three fields and fills the third field with Name when it receives focus.

demo of text onfocus

Focus Event Example Top ↑

const nameInput = document.getElementById("name");

nameInput.addEventListener("focus", () => {
  if (nameInput.value === "") {
    nameInput.value = "Name";
  }
});
<form id="profile-form" action="" method="post">
  <label>Your Userid <input type="text" name="t3"></label><br>
  <label>Your Password <input type="password" name="t2"></label><br>
  <label><strong>Your Name</strong> <input type="text" id="name" name="t1"></label>
</form>

Complete Working Source Top ↑

<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Demo onFocus textbox input</title></head>
<body>
<form id="profile-form" action="" method="post">
  <label>Your Userid <input type="text" name="t3"></label><br>
  <label>Your Password <input type="password" name="t2"></label><br>
  <label><strong>Your Name</strong> <input type="text" id="name" name="t1"></label>
</form>
<script>
const nameInput = document.getElementById("name");

nameInput.addEventListener("focus", () => {
  if (nameInput.value === "") {
    nameInput.value = "Name";
  }
});
</script>
</body>
</html>

Use Focus Without Overwriting User Input Top ↑

The example only inserts the value when the field is empty. Modern forms often use a placeholder or nearby help text instead, because automatically changing a field on focus can surprise users. The focus event is still useful for help text, validation hints, selection, and other UI changes.

Event Handling onKeyPress Mouse event Textarea onClick event




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer