Focus Defocus event for form in JS

Source: Internet
Author: User

Focus Event:
Not all elements have focus events, only elements that are interactive, such as form elements, a tags. Only one element in the page has focus, one focus, and the other is lost, and the document is defaulted.

The example structure is as follows:

<form>
<input type= "text" name= "txt1" id= "txt"/>
<input type= "button" Name= "BTN" value= "click"/>
</form>

JS operation is as follows:

1.form.txt1.focus (); This method does not trigger the onfocus () event If the element has the focus.

2.form.txt1.onfocus=function () {console.log (1); }// The event is triggered when the element receives focus

3.form.txt1.onblur=function () {console.log (2);} Triggers the event when the element loses focus

4.form.btn.onclick=function () { form.txt1.select (); }//Select all text in the input box

5.form.btn.onclick=function () {form.txt1.setSelectionRange (2,5); Form.txt1.focus ();} //Setselectionrange need to be used with focus () to see the effect, where the end position of Setselectionrange is not included, Setselectionrange (Start,end) contains two parameters, One is start: the starting position; one is end: End position.

By default, the text in the input box is selected with the text color blue, and if you want to change the background color, you can use #txt:: selection{ background:pink; } to change



Focus Defocus event for form in JS

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.