CSS Portal

HTML onfocus Event Attribute

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
onfocus
HTML Event AttributeThis event attribute is supported by all modern browsers.
Updated 14th October 2023

Description

The onfocus HTML event attribute specifies a JavaScript function to be executed when an element receives focus. Focus is when an element is selected and can be interacted with, such as when a user clicks on an input field or navigates to a link using the keyboard.

The onfocus attribute can be used on any HTML element, but it is most commonly used on form elements, such as input fields, select boxes, and buttons. This is because form elements are often the focus of user interaction.

Here is an example of how to use the onfocus attribute on an input field:

<input type="text" onfocus="myFunction()">

The myFunction() function will be executed when the user clicks on the input field.

Here is an example of how to use the onfocus attribute on a link:

<a href="index.html" onfocus="this.style.color='red'">Home</a>

When the user navigates to the link using the keyboard, the link text will turn red.

The onfocus attribute can be used to perform a variety of tasks, such as:

  • Focusing the user's attention on an element
  • Changing the appearance of an element
  • Validating form data
  • Submitting a form
  • Performing an AJAX request

Syntax

<element onfocus="script">

Values

  • scriptThe name of the script to use when the event has been triggered.

Example

<!DOCTYPE html> 
<html>
<head>
<title>onfocus event</title>
</head>
<body>
<p>Click on the field, and then next to it. When you click on an element, due to the onfocus event attribute, the script is triggered when the element receives focus, and thanks to the onblur event attribute, the script is launched when the focus is lost.</p>
<input type="text" name="testInput" id="testInput" onblur="blurFunction()" onfocus="focusFunction()">
<script>
function blurFunction() {
document.getElementById("testInput").style.background="khaki";
}
function focusFunction() {
document.getElementById("testInput").style.background="red";
}
</script>
</body>
</html>
Open in editor

Browser Support

The following information will show you the current browser support for the HTML onfocus event attribute. Hover over a browser icon to see the version that first introduced support for this HTML event attribute.

This event attribute is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee