Focus Management in JavaScript

Source: Internet
Author: User

Focus as an important feature of JavaScript, basically interacting with the page is inseparable from the focus. But few people to focus on the management system to do summary induction. This article provides a detailed introduction to the focus management in JavaScript

Focus Element

In the end, which elements can get the focus? By default, only form elements can get focus. Because only form elements can interact

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

It is also helpful to have the non-form element focus, set the TabIndex property to 1 first, and then call the focus () method

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

<div id= "test" style= "Height:30px;width:100px;background:lightgreen" >div</div><button id= "BTN" >    The DIV element obtains the focus </button><script>btn.onclick = function () {test.tabindex =-1;    Test.focus (); }test.onfocus = function () {this.style.background = ' pink ';} </script>

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

Activeelement

The Document.activeelement property is used to manage the DOM focus, preserving the currently focused element

[note] This property IE browser does not support

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

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

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

Get focus

There are 4 ways elements get focus, including page loading, user input (pressing the TAB key), focus () method, and autofocus properties

"1" Page load

By default, when a document is just loaded, a reference to the BODY element is saved in document.activeelement. The value of document.activeelement is null during document loading

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

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

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

"2" User input (press the TAB key)

Users can usually use the TAB key to move the focus and use the SPACEBAR to activate the focus. For example, if the focus is on a link, clicking the spacebar will jump to the link

When it comes to the TAB key, you cannot mention the TabIndex property. The TabIndex property is used to specify whether the current HTML element node is tab-traversed and the priority of the traversal

1. If the Tabindex=-1,tab key skips the current element

2, if tabindex=0, indicates 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, the TAB key is traversed first. A higher value indicates a lower priority

In the following code, when you use the TAB key, the order in which the button receives focus is 2, 5, 1, 3

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

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

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

"3" focus ()

The focus () method is used to set the focal point of the browser to a form field, which activates form fields so that they can respond to keyboard events

[note] As described earlier, if the form element is not set to TabIndex-1, you can also get the focus

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

<span id= "test1" style= "height:30px;width:100px;" >span</span><input id= "test2" value= "input" ><button id= "btn1" >span element get 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>

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

"4" Autofocus

  The Autofocus property is added to the HTML5 form field, so you can automatically move the focus to the corresponding field without JavaScript, as long as you set this property

[note] This property can only be used for form elements, and normal elements do not take effect even if set tabindex= "1"

<input Autofocus value= "ABC" >

Hasfocus ()

The Document.hasfocus () method returns a Boolean value that indicates whether an element in the current document is active or focusable. By detecting whether a document has been focused, you can know if you are interacting with the page

Console.log (Document.hasfocus ());//true//Click on another tab in two seconds to leave the focus out of the current page settimeout (function () {Console.log ( Document.hasfocus ());//false},2000);

Lose focus

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

The function of the blur () method is to remove the focus from the element. When the blur () method is called, the focus is not shifted to a particular element; it simply removes the focus from the element that invokes the method.

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

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

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

Focus Event

The focus event is triggered when the page gets or loses focus. With these events and in conjunction with the Document.hasfocus () method and the Document.activeelement attribute, you can know the whereabouts of the user on the page

The focus event consists of the following 4

Blur

The Blur event is triggered when the element loses focus. This event doesn't bubble.

Focus

The focus event is triggered when the element receives focus. This event doesn't bubble.

Focusin

The Focusin event is triggered when the element receives focus. This event is equivalent to the focus event, but it bubbles

Focusout

The Focusour 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, other browsers support only DOM2-level event handlers, except for the DOM0-level event handlers supported by IE browsers

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

<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 123 div element to get focus </button><button id= "BTN2" > content 123 div element 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>

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

It is known from the running result that the Focusin event can be bubbling while the blur event is not bubbling.

Focus events are often used for form presentation and validation

For example, when you get the focus, you modify the background color, and when you lose focus, you restore the background color and verify

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>

<div id= "box" >    <input id= "INPUT1"  type= "text"  placeholder= "Can only enter the number" >    <input id= "Input2"  type= "text"  placeholder= "can 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 validates numbers     if (TARGET&NBSP;===&NBSP;INPUT1) {         if (!/^\d*$/.test (Target.value.trim ())) {             target.focus ();             tips.innerHTML =  ' can only enter numbers, please re-enter '              settimeout (function () {                 tips.innerHTML =  '              },500);         }    }     //if it is a text box that validates Kanji     if (target === input2) {         if (!/^[\u4e00-\u9fa5]*$/.test (Target.value.trim ())) {             target.focus ();             tips.innerhtml  =  ' can only input Chinese characters, please re-enter '             settimeout ( function () {                 tips.innerhtml =  '             },500);         }    }    }</script >

650) this.width=650; "src="/img/fz.gif "alt=" Copy Code "style=" Margin:0px;float:left;border:none; "/>



Focus Management in JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.