Focus elements
Which elements can gain focus? By default, only form elements can get focus. Because only form elements can interact
<input type="text" value="223">
There is also a way to get the focus of non-form elements. First set tabIndex attribute to -1, and then call focus() method.
<div id="test" style="height:30px;width:100px;background:lightgreen">div</div><button id="btn">div element gets focus</button><script>btn.onclick = function(){ test.tabIndex = -1; test.focus(); }test.onfocus = function(){ this.style.background = 'pink';}</script>activeElement
document.activeElement property is used to manage the DOM focus and saves the elements that currently get the 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 gets 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>Get focus
There are 4 ways for elements to get focus, including page loading, user input (press the tab key), focus() method and autofocus property
【1】Page loading
By default, when the document is just loaded, the reference to the body element is saved in document.activeElement . During document loading, 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 bar to activate the focus. For example, if the focus is on a link, press the space bar at this time and it will jump to the link
When it comes to tab key, we must not mention tabindex attribute. tabindex attribute is used to specify whether the current HTML element node is traversed by the tab key and the priority of the 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 a element does not set tabindex , the default value is 0
3. If tabindex is greater than 0, it means that the tab key is traversed first. The larger the value, the smaller the priority
In the following code, when using the tab key, the order in which the button gets focus is 2, 5, 1, and 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()
focus() method is used to set the focus of the browser to the form field, i.e. activate the form field so that it can respond to keyboard events.
[Note] As mentioned earlier, if it is not a form element, set to tabIndex to -1, you can also get the focus
<span id="test1" style="height:30px;width:100px;">span</span><input id="test2" value="input"><button id="btn1">span element gets focus</button><button id="btn2">input element gets focus</button><script>btn1.onclick = function(){test1.tabIndex=-1;test1.focus();}btn2.onclick = function(){test2.focus();}</script>【4】autofocus
An autofocus property has been added to the HTML5 form field. As long as this property is set, the focus can be automatically moved to the corresponding field without JavaScript.
[Note] This attribute can only be used for form elements. Even if the normal element is set to tabIndex=”-1″ , it will not take effect.
<input autofocus value="abc">
hasFocus()
document.hasFocus() method returns a Boolean value indicating whether any elements in the current document are activated or gained focus. By checking whether the document has gained focus, you can know whether it is interacting with the page.
console.log(document.hasFocus());//true//Click on other tabs within two seconds to make the focus leave the current page setTimeout(function(){ console.log(document.hasFocus());//false},2000);Losing focus
If you use javascript to lose focus, then you need to use blur() method
The function of the blur() method is to remove focus from the element. When calling blur() method, the focus will not be transferred to a specific element; it is just to remove the focus from the element calling the 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
The focus event is triggered when the page gains or loses focus. Using these events and cooperating with document.hasFocus() method and document.activeElement property, you can know the whereabouts of the user on the page.
The focus events include the following 4
1. blur
The blur event is fired when the element loses focus. This event won't bubbling
2. Focus
focus event is fired when the element gets focus. This event won't bubbling
3. Focusin
focusin event is fired when the element gets focus. This event is equivalent to focus event, but it bubbling
4. Focusout
focusour event is fired when the element loses focus. This event is equivalent to the blur event, but it bubbles
[Note] Regarding focusin and focusout events, except for the IE browser supporting DOM0 level event handler, other browsers only support DOM2 level 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">Div element with content 123 gets focus</button><button id="btn2">Div element with content 123 loses focus</button><button id="reset">Restore</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, we can see that focusin event can bubble; while the blur event cannot bubble.
Focus events are often used for form display and verification
For example, when you get the focus, modify the background color; when you lose the focus, restore the background color and verify it.
<div id="box"> <input id="input1" type="text" placeholder="only enter numbers"> <input id="input2" type="text" placeholder="only enter Chinese characters"> <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 that verifies the number if(target === input1){ if(!/^/d*$/.test(target.value.trim())){ target.focus(); tips.innerHTML = 'Only enter numbers, please re-enter' setTimeout(function(){ tips.innerHTML = '' },500); } } //If it is a text box that verifies Chinese characters if(target === input2){ if(!/^[/u4e00-/u9fa5]*$/.test(target.value.trim())){ target.focus(); tips.innerHTML = 'Only enter Chinese characters, please re-enter' setTimeout(function(){ tips.innerHTML = '' },500); } } } }</script>Summarize
The above is to summarize all the content of focus management in Javascript for you. This article is introduced in detail and has certain reference value for your study and work. If you have any questions, you can leave a message to communicate.