jQuery .focus() event

Syntax and Description


.focus(handler)           
.focus()

handler is a function to execute each time the event is triggered. Return value is the jQuery object, for chaining purposes.

jQuery focus bind an event handler to the focus JavaScript event, or trigger that event on an element.

.focus(handler) is a shortcut for .bind('focus', handler). .focus() is a shortcut for .trigger('focus').

We can trigger the event when another element is clicked.


$('#other').click(function() {
    $('#target').focus();
});

Set focus to text box

The following code sets focus to text box after the HTML page is loaded.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from  ww w. ja v  a  2 s.c  o m-->
             $("input").focus();
        });
    </script>
  </head>
  <body>
    <body>
     <p><input type="text" /> <span>focus event fire</span></p>
    </body>
</html>

Click to view the demo

Fire focus event

The following code fires focus event and adds style to the nearby element.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--from  w  ww . j ava  2s. co  m-->
            $("input").focus(function () {
                 $(this).next("span").css('color','red');
            });
        });
    </script>
  </head>
  <body>
    <body>
     <p><input type="text" /> <span>focus event fire java2s.com.</span></p>
    </body>
</html>

Click to view the demo

Set value in case of focus event

The following code sets focus form field and sets its value.


<html>
  <head>
    <script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){<!--  www.  j  a v  a  2  s.  com-->
              $("input").removeAttr("disabled").focus().val("ja va2s.com editable now");
        });
    </script>
  </head>
  <body>
    <body>
      <button>Enable</button>
      <input type="text" disabled="disabled" value="data"/>

  </body>
</html>

Click to view the demo





















Home »
  jQuery »
    jQuery Tutorial »




Basics
Selector
DOM
Event
Effect
Utilities