focus()

The jQuery focus event occurs when an element gains focus. It is generated by a mouse click or by navigating to it.

This event is implicitly used to limited sets of elements such as form elements like <input>, <select> etc. and links <a href>. The focused elements are usually highlighted in some way by the browsers.

The focus method is often used together with blur () method.

Syntax:

snippet
$(selector).focus()

It triggers the focus event for selected elements.

snippet
$(selector).focus(function)

It adds a function to the focus event.

Parameters of jQuery focus() event

Parameter Description
Function It is an optional parameter. It is used to specify the function to run when the element gets the focus.

Example of jQuery focus() event

Let's take an example to demonstrate jQuery focus() event.

snippet
<!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-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>

Output:

Focus starts.. Write your name.

Focus starts.. Write your password.

If you want to stop people from writing in text input box in the above example then try the following code.

It will disable to write in the text box.

snippet
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>focus demo</title>
  <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>
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +