jQuery focus()

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

jQuery 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:

  1. $(selector).focus()  

It triggers the focus event for selected elements.

  1. $(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.

  1. <!doctype html>  
  2. <html lang="en">  
  3. <head>  
  4.   <meta charset="utf-8">  
  5.   <title>focus demo</title>  
  6.   <style>  
  7.   span {  
  8.     display: none;  
  9.   }  
  10.   </style>  
  11.   <script src="https://code.jquery.com/jquery-1.10.2.js"></script>  
  12. </head>  
  13. <body>  
  14.  <p><input type="text"> <span>Focus starts.. Write your name.</span></p>  
  15. <p><input type="password"> <span>Focus starts.. Write your password.</span></p>  
  16.  <script>  
  17. $( "input" ).focus(function() {  
  18.   $( this ).next( "span" ).css( "display", "inline" ).fadeOut( 2000 );  
  19. });  
  20. </script>  
  21.  </body>  
  22. </html>  

Test it Now

Output:

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.

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.   <meta charset="utf-8">  
  5.   <title>focus demo</title>  
  6.   <script src="https://code.jquery.com/jquery-1.10.2.js"></script>  
  7. </head>  
  8. <body>  
  9.  <p><input type="text" value="you can't write"></p>  
  10. <p><input type="password"> </p>  
  11.  <script>  
  12. $( "input[type=text]" ).focus(function() {  
  13.   $( this ).blur();  
  14. });  
  15. </script>  
  16.  </body>  
  17. </html>  

Test it Now