How to use JQuery Event focus() Method
This article describe about jQuery Event focus() Method.
jQuery Event focus() Method
When element gets focus this event occur. Means when you select element by a mouse click or by using "tab_navigation" this event occur.
The focus() trigger the focus event.
Example
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("input").focus(function () {
$("input").css("background-color", "gray");
});
$("input").blur(function () {
$("input").css("background-color", "yellow");
});
});
</script>
</head>
<body>
Enter name: <input type="text" />
<p>If you Click in the input field to get focus, and outside the input field to lose focus</p>
</body>
</html>
|
Output
Note: After click in the input field field get focus and background also change.
Trigger the focus Event
It is occur for the selected element.
Example
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("input").focus(function () {
$("input").css("background-color", "Gray");
});
$("input").blur(function () {
$("input").css("background-color", "yellow");
});
$("#btn1").click(function () {
$("input").focus();
});
$("#btn2").click(function () {
$("input").blur();
});
});
</script>
</head>
<body>
Enter your name: <input type="text" />
<p><button id="btn1">Trigger focus event of input field</button></p>
<p><button id="btn2">Trigger blur event of input field</button></p>
</body>
</html>
|
Output
Note: This is the output of after click trigger focus event button
Bind function to the focus event
When focus event occur to the selected element this function to run.
Syntax
$(selector).focus(function)
|
You may also want to read these related articles Click here
Ask Your Question
Got a programming related question? You may want to post your question here
Programming Answers here