How to efficiently use jQuery Focus & Blur methods

How to efficiently use jQuery Focus & Blur methods
The jQuery Focus method is called when a control gets focus.

Syntax of jQuery Focus Method

a. To trigger the .focus() event:
$(selector).focus()

Example: Trigger focus event of an element on button click

There is a textbox and a button. On the click event of the button the focus event of the textbox is triggered and it gets the focus.

See the below code.

<input type="text" placeholder="write on me" />

<button>Focus</button>
$("button").click(function (e) {
    $("input").focus();
}); 

b. Attach function to focus event.

$(selector).focus(function)

Example: Calling function when the focus of textbox occurs

I have a textbox and a span control. When the textbox gets focus (by clicking on it by mouse), I will show the text – Textbox gets focus on the span element.
<input type="text" />
<span></span>

$("input").focus(function () {
    $("span").text("Textbox gets focus")
}); 

Check the demo & download links:

DEMO DOWNLOAD

Syntax of jQuery Blur Method

The jQuery Blur method is called when the control loses its focus.

a. To trigger the .blur() event:

$(selector).blur()

Example: Trigger blur event of an element on button click

Here I have a textbox and a button. On the click event of the button the .blur() event of the textbox is triggered and it loses the focus.

See the below code.

<input type="text" placeholder="write on me" />
<button>Blur</button>

$("button").click(function (e) {
    $("input").blur();
});
b. Attach function to blur event.
$(selector).blur(function)

Example: Calling function when the blur of textbox occurs

Now I have a textbox and a span control. When the textbox blur happens (by clicking somewhere else on the web page), I will show the text – Textbox gets blue on the span element.
<input type="text" />
<span></span>

$("input").blur(function () {
    $("span").text("Textbox gets blur")
}); 

Check the demo & download links:

DEMO DOWNLOAD

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.

Leave a Reply

Your email address will not be published. Required fields are marked *