DOM event - focus (onfocus)

About

This page is about the focus event. ie how to register a callback function to handle this event

focus means that a HTML element becomes active. More see HTML - Focus (Active element) (and Blur)

The opposite of the focus event is called the blur event.

See also: Moz Doc

Properties

Inheritance

Focus Event Type Inheritance (bubble) Description
focus false the child elements do not inherit the listener
blur false the child elements do not inherit the listener
focusin true the child elements inherit the listener
focusout true Doc

For instance, the focus event listener does not propagate to its children. (ie If you create a focus listener on a window, all elements of the window will not inherit the listener.

Registration

Listener

As an listener

function changeFocus(){
  document.getElementById("radio-2").focus();
}

onFocus = (event) => {
  console.log(event.target.id+" is on focus");
  event.target.style.background = 'pink';    
};

radio1 = document.getElementById("radio-1");
radio1.addEventListener('focus', onFocus);

radio2 = document.getElementById("radio-2");
radio2.addEventListener('focus', onFocus);
<p>Click on Radio1, then Radio2, then the Button
<p><label><input id="radio-1" type="radio" name="radio" value="radio-1"  autofocus />Radio 1</label></p>
<p><label><input id="radio-2" type="radio" name="radio" value="radio-2"  />Radio 2<label></p>
<button onClick="changeFocus()">Focus Dynamically on Radio2</button>

handler

As an handler - The onfocus attribute may be used with the following elements: A, AREA, LABEL, INPUT, SELECT, TEXTAREA, and BUTTON.


Powered by ComboStrap