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
Interested in programming then start with Introduction to ASP.NET Core MVC

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
If you want to quickly create a Modal Popup without Bootstrap then see jQuery Modal PopUp Window with Animation Effects

Share this article -

yogihosting

ABOUT THE AUTHOR

I hope you enjoyed reading this tutorial. If it helped you then consider buying a cup of coffee for me. This will help me in writing more such good tutorials for the readers. Thank you. Buy Me A Coffee

Leave a Reply

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