HTML event attribute onfocus








The onfocus attribute event is triggered when an element gets the focus.

What's new in HTML5

None.

Syntax

<element onfocus="script or Javascript function name">

Supported Tags

All HTML elements, EXCEPT:

<base>, 
<bdo>, 
<br>, 
<head>, 
<html>, 
<iframe>, 
<meta>, 
<param>, 
<script>, 
<style>, 
<title>




Browser compatibility

onfocus Yes Yes Yes Yes Yes

Example

<!DOCTYPE html>
<html>
<body>
<!--from   ww  w  . j a v a2  s.c  o m-->
First name: <input type="text" id="fname" onfocus="myFunction(this.id)">

<script>
function myFunction(x) {
    console.log(x);
}
</script>

</body>
</html>

Click to view the demo





Example 2

The following code shows how to add event listener to input text focus on event.

<html>
<head>
<script language="JavaScript" type="text/javascript">
  function DisplayMsg(NumVal) {<!-- ww  w .j a va  2 s . com-->
    if (NumVal == 1) {
      alert("Type your name in the field");
    }
    if (NumVal == 2) {
      alert("Type your phone number in the field");
    }
  }
</script>
<title>Keyboard Event</title>
</head>
<body>
  <form name="form1">
    <b>Name:</b>&nbsp; <input type="text" name="text1"
      onFocus="DisplayMsg(1)" size="20">
    <P>
      <b>Phone:</b> &nbsp;<input type="text" name="text2"
        onFocus="DisplayMsg(2)" size="20">
    </p>
  </form>
</body>
</html>

Click to view the demo