Home > Article > Web Front-end > Introduction to onblur and onfocus event application in JS_Basic knowledge
In HTML pages, visual elements such as buttons and text boxes have events for having and losing focus. These events can trigger preset operations in response to mouse or keyboard actions. This article takes the text box gaining and losing focus as an example to briefly explain the application of onfocus and onblur.
1. onfocus (get focus event)
When a text box gets focus, the text inside it is like the Baidu search input box on the "Hao123" website. is automatically selected, such an operation can be achieved using onfocus.
When the mouse pointer moves over the following text box, all the text inside will be selected:
Please enter the URL
How to do this? Look at the following code and explanation:
In the code, the JS statement for the onmousemove (mouse pointer passing) event is embedded in the input tag. The this.focus() after the equal sign means that it gets the focus; The sign is that the input cursor will appear in the text box, but in order to select all the text in it, we have to use this.select() statement, which means to select all the text in the text box.
2. onblur (lost focus event)
We often detect whether the text box has been entered correctly. The detection is usually performed after the user clicks the submit button. In fact, When the control loses focus, we can perform this detection work in real time. In this case, the onblur event comes in handy.
The following example has four text boxes. If there is no click on any of them, nothing will happen. However, when you click on any of them, it will have focus ( The input cursor is inside), if you input nothing and click somewhere else to make it lose focus, a warning will pop up, try
Name
Gender
Age
Address
The following is the code and explanation:
Form code