Detailed Explanation of JavaScript onblur and onfocus Events

  • 2021-11-14 05:06:05
  • OfStack

In an html page, visual elements, such as buttons, text boxes, and so on, have both in-focus and out-of-focus events that trigger preset actions in response to mouse or keyboard actions. This article briefly explains the application of onfocus and onblur by taking the text box gain and lose focus as an example.

1. onfocus (Getting Focus Events)

When a text box gets the focus, the text in it is automatically selected just like Baidu search input box on "Hao 123" website, which can be realized by onfocus.

The following text box, when the mouse pointer moves over, all the text in it is selected:

Please enter the URL

How is this done? Look at the following code and explanation:


<input type="text"name="url" value="http://www.gxblk.com" size="30" O nm O usem O ve="this.focus();this.select();">

In the code, the input tag embeds the JS statement of the onmousemove (mouse pointer passing by) event, and the this. focus () after its equal sign means that it gets the focus; The sign of focus is that the input cursor will appear in the text box, but to make all the text in it selected, we have to use the this. select () statement, which means to select all the text in the text box.

2. onblur (Out of Focus Event)

We often check whether the text box has been entered correctly. The check is usually done after the user clicks the submit button. In fact, when the control loses focus, we can do this check in real time, so the onblur event comes in handy.

The following example has four text boxes, Nothing will happen if you haven't clicked any one of them yet, but when you click any one of them to make it have focus (the input cursor is inside), if you don't enter anything and click somewhere else to make it lose focus, a warning will pop up. Try it

Name

Gender

Age

Address

Here's the code and explanation:

Form code


<form name="blur_test">

   <p> Name  <input type="text" name="name"value="" size="30" O nblur="chkvalue(this)"><br>

     Gender  <inputtype="text" name="sex" value=""size="30"  O nblur="chkvalue(this)"><br>

     Age  <inputtype="text" name="age" value=""size="30"  O nblur="chkvalue(this)"><br>

     Address  <inputtype="text" name="addr" value=""size="30"  O nblur="chkvalue(this)"></p>

</form>

JS code


<scriptlanguage="javascript">
function chkvalue(txt) {
   if(txt.value=="") alert(" You must fill in the text box !");

}
</script>

In the form code, every square box code is embedded with an onblur JS statement, which calls the custom function chkvalue (this) in the following JS code, which means that when the text box loses focus, it calls chkvalue () function; This chkvalue () function detects whether the text box is empty, and if so, a warning window pops up. The function has one argument (txt), corresponding to the argument (this) that the previous text box called the function, that is, itself.


Related articles: