jQuery focus()

The jQuery focus event is implicitly used for a limited set of elements like input, select, a href, etc. As the name suggests, this event occurs when an element gains focus.

Syntax:

To trigger the focus event for selected elements.

$(selector).focus()

To add a function to the focus event.

$(selector).focus(function)

Function:

  • It is an optional parameter.
  • The function parameter specifies the function to run when the event occurs.

Example1:

<!DOCTYPE html>
<html>
<head>
<style>
span {
display: none;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p><input type="text"> <span>Focus starts.. Write your name.</span></p>
<p><input type="password"> <span>Focus starts.. Write your password.</span></p>
<script>
$( "input" ).focus(function() {
$( this ).next( "span" ).css( "display", "inline" ).fadeOut( 2000 );
});
</script>
</body>
</html>

Example2:

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p><input type="text" value="you can't write"></p>
<p><input type="password"> </p>
<script>
$( "input[type=text]" ).focus(function() {
$( this ).blur();
});
</script>
</body>
</html>