English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Detailed Summary of Focus Management in Javascript

Focus Element

Which elements can gain focus? By default, only form elements can gain focus. Because only form elements can be interactive

<input type="text" value="223">

It is also possible to make non-form elements gain focus. First, set the tabIndex attribute to-1Then call the focus() method

<div id="test" style="height:30px;width:100px;background:lightgreen">div</div>
<button id="btn">div element gains focus</button>
<script>
btn.onclick = function(){
 test.tabIndex = -1;
 test.focus(); 
}
test.onfocus = function(){
 this.style.background = 'pink';
}
</script>

activeElement

The document.activeElement attribute is used to manage DOM focus and saves the current element that has gained focus

[Note] This property is not supported by IE browser

<div id="test" style="height:30px;width:100px;background:lightgreen">div</div>
<button id="btn">div element gains focus</button>
<script>
console.log(document.activeElement);//<body>
btn.onclick = function(){
 console.log(document.activeElement);//<button>
 test.tabIndex = -1;
 test.focus(); 
 console.log(document.activeElement);//<div>
}
</script>

Focus obtained

There are several ways for an element to gain focus4types, including page loading, user input (pressing the tab key), focus() method, and autofocus attribute

【1】Page loading

By default, when the document is just loaded, the reference saved in document.activeElement is the body element. During the document loading period, the value of document.activeElement is null

<script>
console.log(document.activeElement);//null
</script>
<body>
<script>
console.log(document.activeElement);//<body>
</script>
</body>

【2】User input (press the tab key)

Users can usually use the tab key to move the focus, and use the space key to activate the focus. For example, if the focus is on a link, pressing the space key will jump to the link

When it comes to the tab key, it is impossible not to mention the tabIndex attribute. The tabIndex attribute is used to specify whether the current HTML element node is traversed by the tab key and the priority of traversal

1, if tabIndex=-1, the tab key skips the current element

2, if tabIndex=0, it means that the tab key will traverse the current element. If an element is not set tabIndex, the default value is 0

3, if tabIndex is greater than 0, it means that the tab key traverses in priority. The higher the value, the lower the priority

In the following code, the order in which the button receives focus when using the tab key is2,5,1,3

<div id="box">
 <button tabindex="3">1</button>
 <button tabindex="1">2</button>
 <button tabindex="0">3</button>
 <button tabindex="-1">4</button>
 <button tabindex="2">5</button> 
</div>
<script>
box.onkeyup = function(){
 document.activeElement.style.background = 'pink';
}
</script>

【3】focus()

The focus() method is used to set the focus of the browser to the form field, i.e., to activate the form field so that it can respond to keyboard events

[Note] As introduced earlier, if it is not a form element, set tabIndex to-1,can also gain focus

<span id="test1" style="height:30px;width:100px;">span</span>
<input id="test2" value="input">
<button id="btn1">span element gains focus</button>
<button id="btn2">input element gains focus</button>
<script>
btn1.onclick = function(){test1.tabIndex=-1;test1.focus();}
btn2.onclick = function(){test2.focus();}
</script>

【4】autofocus

  HTML5A new autofocus attribute has been added to form fields. By setting this attribute, focus can be automatically moved to the corresponding field without JavaScript

[Note] This attribute can only be used for form elements, even if the tabIndex is set for ordinary elements-1″also does not take effect

<input autofocus value="abc">

hasFocus()

The document.hasFocus() method returns a boolean value indicating whether there is an element activated or focused within the current document. By detecting whether the document has gained focus, you can determine whether you are interacting with the page

console.log(document.hasFocus());//true
//Click on other tabs within two seconds to move focus away from the current page
setTimeout(function(){
 console.log(document.hasFocus());//false
},2000);

Lose focus

If you use JavaScript to make an element lose focus, you must use the blur() method

The blur() method's function is to remove focus from an element. When calling the blur() method, it does not transfer focus to a specific element; it simply removes focus from the element that called this method

<input id="test" type="text" value="123">
<button id="btn1">input element gains focus</button>
<button id="btn2">input element loses focus</button>
<script>
btn1.onclick = function(){test.focus();}
btn2.onclick = function(){test.blur();}
</script>

Focus events

Focus events are triggered when the page gains or loses focus. By using these events in conjunction with the document.hasFocus() method and the document.activeElement property, you can track the user's actions on the page

The focus events include the following4个

1、blur

The blur event is triggered when an element loses focus. This event does not bubble

2、focus

The focus event is triggered when an element gains focus. This event does not bubble

3、focusin

The focusin event is triggered when an element gains focus. This event is equivalent to the focus event, but it bubbles

4、focusout

focusout event is triggered when the element loses focus. This event is equivalent to the blur event, but it bubbles

[Note] For focusin and focusout events, in addition to IE browser supporting DOM0 level event handlers, other browsers only support DOM2level event handler

<div id="box"style="display:inline-block;padding:25px;background-color:lightgreen;">
 <div id="boxIn" style="height: 50px;width: 50px;background-color:pink;">123</div>
</div>
<button id="btn1">Content is123the div element gains focus</button>
<button id="btn2">Content is123the div element loses focus</button>
<button id="reset">Reset</button>
<script>
reset.onclick = function(){history.go();}
//focus() method
btn1.onclick = function(){
 boxIn.tabIndex= -1;
 boxIn.focus();
}
//blur() method
btn2.onclick = function(){
 boxIn.blur();
}
//focusin event
if(boxIn.addEventListener){
 boxIn.addEventListener('focusin',handler) 
}else{
 boxIn.onfocusin = handler;
}
function handler(){
 this.style.backgroundColor ='lightblue';
}
if(box.addEventListener){
 box.addEventListener('focusin',handler) 
}else{
 box.onfocusin = handler;
} 
//blur event
function fnBlur(){
 this.style.backgroundColor = 'orange';
}
boxIn.onblur = fnBlur;
box.onblur = fnBlur;
</script>

From the running results, it can be seen that the focusin event can bubble; while the blur event cannot bubble 

Focus events are commonly used for form display and validation

For example, change the background color when gaining focus; restore the background color and validate when losing focus

<div id="box">
 <input id="input"}1" type="text" placeholder="Only numeric input is allowed">
 <input id="input"}2" type="text" placeholder="Only Chinese characters can be entered"> 
 <span id="tips"></span>
</div>
<script>
if(box.addEventListener){
 box.addEventListener('focusin',fnIn);
 box.addEventListener('focusout',fnOut);
}else{
 box.onfocusin = fnIn;
 box.onfocusout = fnOut;
}
function fnIn(e){
 e = e || event;
 var target = e.target || e.srcElement;
 target.style.backgroundColor = 'lightgreen';
}
function fnOut(e){
 e = e || event;
 var target = e.target || e.srcElement;
 target.style.backgroundColor = 'initial';
 //If it is a text box for verifying numbers
 if(target === input1{
 if(!/^\d*$/.test(target.value.trim())){
 target.focus();
 tips.innerHTML = 'Only numbers can be entered, please re-enter'
 setTimeout(function(){
 tips.innerHTML = ''
 },500);
 }
 }
 //If it is a text box for verifying Chinese characters
 if(target === input2{
 if(!/^[\u4e00-\u9fa5]*$/.test(target.value.trim())){
 target.focus();
 tips.innerHTML = 'Only Chinese characters can be entered, please re-enter'
 setTimeout(function(){
 tips.innerHTML = ''
 },500);
 }
 } 
}
</script>

Summary

This is the summary of all the focus management in JavaScript for everyone, this article is very detailed and has certain reference value for everyone's study and work, if you have any questions, you can leave a message for communication.

You May Also Like