How to transfer focus

How to transfer focus

Knowledge Base Hits: 67

When developing the scenario of behavior of the user on the HTML page happens it is necessary to mark the input cursor in the certain element placed on this page. As, for example, it is made on the homepage of the search engine Rambler where the cursor when loading the page is installed in the entry field of a search query. It is possible to realize such transfer of focus to the set element by means of the JavaScript language.

Instruction

1. Use focus property () the necessary element of the page, for transfer of input focus to it. For example, to place the cursor in a text field with the identifier MainTextField right after loading of the page in the visitor's browser, it is possible to place the corresponding JavaScript-code in onload attribute of the body tag: <body onload= "" document.getElementById ('MainTextField') .focus ()""> is used Here the DOM standard getElementById method (Document Object Model is "Object Model of the Document"), which carries out search of the necessary element in its identifier (id). Input with help properties focus is transferred to the found element focus.

2. If it is required to transfer focus, for example, when pressing of the button placed in the page, then the corresponding JavaScript-code can be placed in the attribute defining behavior of the button at click on it - onclick. The tag of such button can be written down, for example, so: <()""> to transfer to button onclick= "" document.getElementById ('MainTextField') .focus focus </button> in the Same way it is possible to place the code of transfer of focus to tags of the majority of elements in which use of onclick attribute is allowed.

3. Use onblur attribute if it is necessary to transfer focus not on click, and on movement of focus from any element to the following. For example, if the user filled one field of a form and passes to the following, then it is possible to translate forcibly input focus not to the element following one after another, and to that which you will specify in the code placed in onblur attribute: <input type= "" text"" onblur= "" document.getElementById ('MainTextField') .focus ()""/>

4. Place in onblur attribute the conditional operator if it is required to transfer focus depending on performance of any condition. For example, if the field of a form has to be surely filled, it is possible to place check in its onblur attribute whether some value and if the answer negative is entered, to return input focus to the same field: <input type= "" text"" id= "" MainTextField"" of onblur= "" if (this.value =='') this.focus ()""/>

Author: «MirrorInfo» Dream Team

Print