jQuery focus() Method
Last Updated :
14 Dec, 2023
jQuery focus() is an inbuilt method that is used to focus on an element. The element gets focused by the mouse click or by the tab-navigating button.Â
Syntax:
$(selector).focus(function)
Here selector is the selected element.Â
Parameter: It accepts an optional parameter in the form of a callback function which will be called once the focus event occurs.
Example 1: The below example explains the focus() method with a callback function passed to it.
HTML
<!DOCTYPE html>
< html >
< head >
< style >
span {
display: none;
}
body {
width: 35%;
height: 50px;
border: 2px solid green;
padding: 35px;
margin: 10px;
}
</ style >
< script src =
</ script >
</ head >
< body >
< p >
< input type = "text" > < span >focused</ span >
</ p >
< script >
$("input").focus(function () {
$(this).next("span").css(
"display", "inline");
});
</ script >
</ body >
</ html >
|
Output:Â
Example 2: In the below example, the focus() method is invoked without any parameters.
HTML
<!DOCTYPE html>
< html >
< head >
< style >
span {
display: none;
}
body {
width: 30%;
height: 50px;
border: 2px solid green;
padding: 35px;
margin: 10px;
}
</ style >
< script src =
</ script >
</ head >
< body >
< p >
< input type = "text" > < span >focused</ span >
</ p >
< script >
$("input").focus();
</ script >
</ body >
</ html >
|
Output:Â
Share your thoughts in the comments
Please Login to comment...