HTML - Focus (Active element) (and Blur)

1 - About

The focus is the element actually active on a HTML page through:

  • after a tab
  • after a page load
  • or dynamically
The opposite of focus is called blur (ie delete the focus).

3 - Attribute

3.1 - Tabindex

tabindex global attribute:

  • enable a element to be focusable
  • indicate the tab order
  • remove a element from the tab order

3.2 - Autofocus

The element with the autofocus=true attribute will be focused after a fetch.

This is generally:

  • after a page load
  • but you can also focus on single element (such as an image)

If put on more than one element, the first one with the attribute receives focus .

4 - Management

4.1 - Get / Select

4.1.1 - Javascript

Example:


function whereIsTheFocus(){
  console.log("The active element on this page has");
  console.log("  * the id"+parent.document.activeElement.id);
  console.log("  * the node name "+parent.document.activeElement.nodeName);
}
console.log("The focus when the page load is");
whereIsTheFocus();


<p>Click on the below button to see the focus changing</p>
<button onClick="whereIsTheFocus()">Where is the focus now ?</button>

4.1.2 - Selector

With action pseudo class :focus, you can apply style to the focused element.

Example:


textarea:focus {
  background-color: aliceblue;
}

  • The textarea that will change when ti will get the focus (by clicking on it for instance)

<textarea cols="30" rows="5">
Click on me to focus and change the background color
</textarea>

4.2 - Set

You can modify the focus

  • by hitting the tab key
  • by clicking on a element
  • dynamically with the focus function
  • at page load (element load) with the autofocus=true attribute

4.2.1 - focus function


document.getElementById("radio-2").focus();

4.3 - Disable

To remove an element from the tab order (focusable by keyboard), set the tabindex to -1 (The element is still focusable by script)


tabindex="-1"

4.4 - Enable

Not all element are by default focusable, only interactive elements (like links, form controls) get focused such as:

To make an element focusable, you need to set the tabindex to a positive value.

4.5 - Event callback function

4.6 - Reset / Loose / Blur

  • Es

document.activeElement.blur()

  • Jquery:

$(document.activeElement).blur();

4.7 - Track

You can track the active element.

  • with a live expression in devtool: Ref


/**
 * doc is the document
 */ 
function printActiveElement(active) {
    const selector = active.getAttribute('id') ? `#${active.id}` : `${active.localName}.${active.className.replace(/\s/g, '.')}`;
    console.log("Active Element Selector: "+selector);
}
parent.window.addEventListener('focusin', e => {
     console.log("The active element has changed");
     const active = e.target;
     printActiveElement(active);
});


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap