Introduction to JQUERY - How to Attach a Function to a focus() method

Guest Posts Paolo Nikko Nuñal

You might notice that every time you enter something on an input box there is this some sort of highlight that indicates you are writing on that specific box. We'll, JQUERY in fact has this method called focus() that actually attaches a function to the event everytime you set "focus" into it. The focus() method usually is attached to <input> fields and are commonly used by many web developers to create an event especially when they enter something in a particular input box.

Syntax:

$(selector).focus([FUNCTION])

FUNCTION - (OPTIONAL) Specifies the function you want to call when the focus event starts or gets called.

Code


<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
      $(document).ready(function(){
          $("#name").focus(function(){
               $("#name_focus").css("display","inline").fadeOut(3000);
          });
          $("#age").focus(function(){
               $("#age_focus").css("display","inline").fadeOut(3000);
          });
 });
</script>
<style>
span
{
display:none;
}
</style>
</head>
<body>
<input id="name"> Name:
<span id="name_focus">Focused on name box</span>
<input id="age"> Age:
<span id="age_focus">Focused on age box</span>
</body>
</html>


Once you select something on the inbox, it will automatically trigger the hidden span stating that you have focused on that box. This is especially useful if you are planning on having triggers set during focus. You can do some actions here like processing data and the like. In our second tutorial, we will be focusing on the blur() method that does exactly the opposite of focus().