Get the App
SLTechnology News&Howtos  ›  Development  › 

How jquery gets and loses focus events

Shulou Source: shulou.com Published: 2022-06-02 13:26:25 10月04日 Update

This article introduces the knowledge of "how jquery gains and loses focus". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

In jquery, you can use the focus () method to get the focus event, the syntax "$(selector) .focus ()", and the syntax "$(selector) .blur ()" to lose the focus event using the blur () method.

The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.

If there are some form elements in the front-end site for users to fill in, we can use JQ to get focus events and lose focus events to give users some prompts. Today we will talk about the use of events that gain focus and lose focus under JQuery.

Jquery focus () gets the focus event

The focus () method: when you select an element with a mouse click or navigate to it with the tab key, the element gets focus.

Syntax:

(selector) .focus ()

Copy

Example: input input box changes the color of its border when it gets focus

Sample code:

$('# mochu') .focus (function () {$(this) .css ('border-color','red');})

Copy

When the mouse is moved into the input and clicked, the input element changes to the following form

The jq focus () event, which adds a CSS style to input

Copy

Jquery blur () lose focus event

The blur () method: a blur event occurs when an element loses focus

Syntax:

(selector) .blur ()

Copy

Example: after input loses focus, the contents of the input box pop up

Sample code:

$('# mochu') .blur (function () {alert ($(this). Val ());})

Copy

The running result is shown in the figure:

Use jq blur () lose focus event to validate user input

The blur () loss of focus event in JQuery can be used to check whether what the user typed in the input input box is valid, such as the following code, which gives a prompt if the user enters less than five characters

Sample code:

$('# mochu') .blur (function () {if ($(this). Val (). Length < 5) {alert ('too few words, enter a few more');}}); that's all for "how jquery gets and loses focus". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Focus event content input element method user code syntax example more knowledge website mouse prompt legal practical learned next usage Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno vpn Microsoft MySQL Linux