Example of focus event usage in jQuery

  • 2020-05-10 17:37:33
  • OfStack

This article illustrates the use of focus events in jQuery as an example. Share with you for your reference. The specific analysis is as follows:

An focus event is triggered when an element gets focus or when the focus() method is called.

A complete event process, not only has to be able to trigger the event conditions, but also has an event handler.
You can bind event handlers for focus events using the focus() method. Such as:

$("input").focus(function(){$(this).css("backgroundColor","red")})

The code above binds the function function as an event handler to the focus event via the focus() method. This function is called when the focus event is triggered.
Example code:


<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="//www.ofstack.com/" />
<title>focus The event - The home of the script </title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("input").focus(function(){
    $(this).css("backgroundColor","red")
  })
}) 
</script>
</head>
<body>
<div>
<ul>
  <li> The user name :<input type="text" name="username" /></li>
  <li> password :<input type="password" name="userpassword" /></li>
</ul>
</div>
</body>
</html>

The above code registers the focus event handler for the input element, which sets the background color of the text box when it gets focus.

I hope this article has been helpful to your jQuery programming.


Related articles: