onfocus event

Definition and Usage

The onfocus event occurs when an element gains focus.

The onfocus event is most commonly used with <input>, <select>, and <a>.

Tip: The onfocus event is used with onblur EventOn the contrary.

Tip: The onfocus event is similar to onfocusin Event. The main difference is that the onfocus event does not bubble. Therefore, if you want to determine whether an element or its child element has gained focus, you can use the onfocusin event. However, you can use the onfocus event addEventListener() methodof useCapture parameters to achieve this.

Instance

Example 1

Execute JavaScript when the input field gains focus:

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

Try It Yourself

More TIY examples are at the bottom of the page.

Syntax

In HTML:

<element onfocus="myScript">

Try It Yourself

In JavaScript:

object.onfocus = function(){myScript};

Try It Yourself

In JavaScript, use the addEventListener() method:

object.addEventListener("focus", myScript);

Try It Yourself

Note:Internet Explorer 8 or earlier versions do not support addEventListener() method

Technical details

Bubble: Not supported
Cancelable: Not supported
Event types: FocusEvent
Supported HTML tags: All HTML elements except: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style> and <title>
DOM version: Level 2 Events

Browser support

Events Chrome IE Firefox Safari Opera
onfocus Supported Supported Supported Supported Supported

More examples

Example 2

Use "onfocus" and "onblur" events together:

<input type="text" onfocus="focusFunction()" onblur="blurFunction()">

Try It Yourself

Example 3

Clear the focused input field:

/* When the input field gains focus, replace its current value with an empty string */
<input type="text" onfocus="this.value=''" value="Blabla">

Try It Yourself

Example 4

Event delegation: Set the useCapture parameter of addEventListener() to true:

<form id="myForm">
  <input type="text" id="myInput">
</form>
<script>
var x = document.getElementById("myForm");
x.addEventListener("focus", myFocusFunction, true);
x.addEventListener("blur", myBlurFunction, true);
function myFocusFunction() {
  document.getElementById("myInput").style.backgroundColor = "yellow"; 
}
function myBlurFunction() {
  document.getElementById("myInput").style.backgroundColor = ""; 
}
</script>

Try It Yourself

Example 5

Event delegation: Using the focusin event (not supported by Firefox):

<form id="myForm">
  <input type="text" id="myInput">
</form>
<script>
var x = document.getElementById("myForm");
x.addEventListener("focusin", myFocusFunction);
x.addEventListener("focusout", myBlurFunction);
function myFocusFunction() {
  document.getElementById("myInput").style.backgroundColor = "yellow"; 
}
function myBlurFunction() {
  document.getElementById("myInput").style.backgroundColor = ""; 
}
</script>

Try It Yourself