onfocus-händelsen

Definition och användning

onfocus-händelsen inträffar när ett element får fokus.

onfocus-händelsen används ofta tillsammans med <input>, <select> och <a>.

Tips: onfocus-händelsen och onblur-händelseomvänd.

Tips: onfocus-händelsen liknar onfocusin-händelse. Huvudskillnaden är att onfocus-händelsen inte bubblar. Därför kan du använda onfocusin-händelsen för att bestämma om en element eller dess underliggande element har fått fokus. Men du kan använda addEventListener() metodens useCapture Parameter för att uppnå detta.

Exempel

Exempel 1

Kör JavaScript när inmatningsfältet får fokus:

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

Prova själv

Mer TIY-exempel finns längre ner på sidan.

Syntax

I HTML:

<element onfocus="myScript">

Prova själv

I JavaScript:

object.onfocus = function(){myScript};

Prova själv

I JavaScript, använda addEventListener() metoden:

object.addEventListener("focus", myScript);

Prova själv

Kommentar:Internet Explorer 8 eller tidigare versioner stöder inte addEventListener() metoden

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 Support Support Support Support Support

More examples

Example 2

Use "onfocus" and "onblur" events together:

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

Prova själv

Example 3

Clear the input field that has received focus:

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

Prova själv

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>

Prova själv

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>

Prova själv