Horje
HTML onfocus Event Attribute
The onfocus event attribute in HTML triggers a script or function when an element receives focus. This typically occurs when a user clicks on or navigates to an element using the keyboard (e.g., using the Tab key).
 

Example of HTML onfocus Event Attribute

It executes a JavaScript when an input field gets focus.
index.html
Example: HTML
 <input type="text" id="fname" onfocus="myFunction(this.id)"> 

Output should be:

Example of HTML onfocus Event Attribute

Definition and Usage of HTML onfocus Event Attribute

The onfocus attribute fires the moment that the element gets focus.

Onfocus is most often used with <input>, <select>, and <a>.

Tip: The onfocus attribute is the opposite of the onblur attribute.

Browser Support of HTML onfocus Event Attribute

Browser Support of HTML onfocus Event Attribute

Syntax of HTML onfocus Event Attribute

<element onfocus="script">

Attribute Values of HTML onfocus Event Attribute

Value Description
script The script to be run on onfocus

Technical Details of HTML onfocus Event Attribute

Supported HTML tags: All HTML elements, EXCEPT: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title>

How to Execute a JavaScript when an input field gets focus

A function is triggered when one of the input fields get focus. The function changes the background-color of the input field.

index.html
Example: HTML
<!DOCTYPE html>
<html>
<body>

<p>A function is triggered when one of the input fields get focus. The function changes the background-color of the input field.</p>
First name: <input type="text" id="fname" onfocus="myFunction(this.id)"><br>
Last name: <input type="text" id="lname" onfocus="myFunction(this.id)">

<script>
function myFunction(x) {
  document.getElementById(x).style.background = "yellow";
}
</script>

</body>
</html>

Output should be:

How to Execute a JavaScript when an input field gets focus

How to use "onblur" together with the "onfocus" attribute

When you enter the input field, a function is triggered which sets the background color to yellow. When you leave the input field, a function is triggered which sets the background color to red.

index.html
Example: HTML
 <input type="text" onfocus="focusFunction()" onblur="blurFunction()"> 

Output should be:

How to use "onblur" together with the "onfocus" attribute




html event attributes

Type:
Develop
Category:
Web Tutorial
Sub Category:
HTML Form Events Attribute
Uploaded by:
Admin


Read Article
https://develop.horje.com/learn/1434/reference