onfocus Event

Example

Call a function when an input field gets focus:

<input type="text" onfocus="myFunction()">
Try it Yourself »

Description

The onfocus event occurs when an element gets focus.

The onfocus event is often used on input fields.


Focus Based Events

EventOccurs When
focusAn element gets focus
blurAn element loses focus
focusinAn element gets focus
focusoutAn element loses focus

See Also:

The Focus Event Object


Syntax

In HTML:

<element onfocus="myScript">
Try it Yourself »

In JavaScript:

object.onfocus = function(){myScript};
Try it Yourself »

In JavaScript, using the addEventListener() method:

object.addEventListener("focus", myScript);
Try it Yourself »

Technical Details

Bubbles: No
Cancelable: No
Event type: FocusEvent
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

onfocus is a DOM Level 2 (2001) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11


More Examples

Example

Using onfocus and onblur:

<input type="text" onfocus="focusFunction()" onblur="blurFunction()">
Try it Yourself »

Example

Clear input field on focus:

<input type="text" onfocus="this.value=''" value="Blabla">
Try it Yourself »

Example

Event delegation: using focus and blur events:

Set useCapture parameter of addEventListener() to true:

<form id="myForm">
  <input type="text" id="myInput">
</form>

<script>
let 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

Event delegation: using focusin and focusout events:

<form id="myForm">
  <input type="text" id="myInput">
</form>

<script>
let 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 »

Copyright 1999-2023 by Refsnes Data. All Rights Reserved.