jQuery focus() function is used to bind an event handler to the "focus" JavaScript event or trigger that event on an element.
Syntax
$(selector).focus()
It triggers the focus event for selected elements.
$(selector).focus(function)
It adds a function to the focus event.
Example
Fire focus.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>focus demo</title>
<style>
span {
display: none;
}
</style>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>
<body>
<p><input type="text"> <span>focus fire</span></p>
<p><input type="password"> <span>focus fire</span></p>
<script>
$("input").focus(function() {
$(this).next("span").css("display", "inline").fadeOut(1000);
});
</script>
</body>
</html>
More Examples
To stop people from writing in text input boxes, try:
$( "input[type=text]" ).focus(function() {
$( this ).blur();
});
To focus on a login input box with id 'login' on page startup, try:
$( document ).ready(function() {
$( "#login" ).focus();
});
Comments
Post a Comment