.focus()

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 www . j  ava  2 s  .  c  om-->
             $("input").focus();
        });
    </script>
  </head>
  <body>
    <body>
     <p><input type="text" /> <span>focus event fire</span></p>
    </body>
</html>

Click to view the demo

The code above generates the following result.

.focus()

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 w  w.  j a  v  a2 s  . c  o  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

The code above generates the following result.

.focus()

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(){<!--from   w ww  . jav a2  s .  c  o  m-->
              $("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

The code above generates the following result.

.focus()
Home »
  Javascript Tutorial »
    jQuery Reference »
      Event
Javascript Tutorial Event
Event
Event attributes
event.keycode
event.clientX/clientY
pageX/pageY
Cancel event
Event target
bind
.blur()
.change()
.click()
.error()
.dblclick()
.delegate()
.die()
.focus()
.hover()
.keydown()
.keypress()
.keyup()
.live()
.load()
.mousedown()
.mouseenter()
.mouseleave()
.mousemove()
.mouseover()
.mouseout()
.mouseup()
.off()
.on()
.one()
.ready()
.resize()
.scroll()
.select()
.submit()
.toggle()
.trigger()
.triggerHandler()
.unbind()
.undelegate()
.unload()