.focus()
In this chapter you will learn:
- Syntax and Description for .focus() event
- How to set focus to text box
- How to fire focus event
- How to set value in case of 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><!-- j av a2 s . co m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input").focus();
});
</script>
</head>
<body>
<body>
<p><input type="text" /> <span>focus event fire</span></p>
</body>
</html>
Fire focus event
The following code fires focus event and adds style to the nearby element.
<html><!-- j av a2 s .c o m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("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>
Set value in case of focus event
The following code sets focus form field and sets its value.
<html><!-- j av a2s .co m-->
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("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>
Next chapter...
What you will learn in the next chapter:
- Syntax and Description for .hover() event
- How to add hover action to element
- How to use hover action to add and remove class
- How to use hover action to hide tag
- How to use hover to fade in and out
- How to use hover event with lists