w3resource logo

HTML onfocus attribute - HTML tutorials

HTML onfocus attribute

Secondary Nav


The purpose of the HTML onfocus attrwibute is to indicate the user agent that the element has got focus. When the element gets focus, if onfocus is used, a script is executed.

Supported elements

HTML onfocus attribute supports a, area, button, input, label, select, textarea elements.

onfocus attribute can be effectively applied to form elements.


<ElementName onfocus="value" >.....</ElementName>

Where ElementName is any supported element.

Type of value



A script which is to be executed.

Default value

There is no default value of HTML onfocus attribute.

Supported doctypes

HTML 4.01 strict, HTML 4.01 transitional, HTML 4.01 frameset.

Example of HTML onfocus attribute with form elements

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Example of HTML onfocus attribute with form elements</title>
<form name="onfocus_example" action=""> 
Name : <input type="text" name="name" onfocus="alert('name field has got focus')"><br>
<label>Favorite Sports </label> 
<select name="favourite_sports" onfocus="alert('favourite_sports field has got focus')">
<option value="Soccer">Soccer</option>
<option value="Hockey">Hockey</option>
<option value="Tennis">Tennis</option> 
<option value="Golf">Golf</option> 
<label>Describe yourself in short : </label> <br/><textarea cols="10" rows="10" name="describe_ yourself" onfocus="alert('describe_ yourself field has got focus')"> </textarea><br>
<button type="button" name="submit">Submit</button>


html onfocus attribute with form elements

View this example in a separate browser window

Example of HTML onfocus attribute with form elements

Join our Question Answer community to learn and share your programming knowledge.