jQuery focus and blur Events


focus


When you tab or click into a text field, it gives the field focus. In other words, the browser’s attention is now focused on that page element. Likewise, selecting a radio button, or clicking a checkbox, gives those elements focus. You can respond to the focus event using JavaScript. For example, you could add a helpful instruction inside a text field - "Type your full name." When a visitor clicks in the field (giving it focus), you can erase these instructions, so he has an empty field he can fill out.

blur


The blur event is the opposite of focus. It is triggered when you exit a currently focused field, by either tabbing or clicking outside the field. The blur event is another useful time for form validation. For example, when someone types her email address in a text field, then tabs to the next field, you could immediately check what she has entered to make sure it is a valid email address.

Let us learn with a simple example.


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-1.8.0.min.js">
</script>
<script>
$(document).ready(function(){
  $("input").focus(function(){
   $("span").text("Focus Established"); 
  });

 $("input").blur(function(){
   $("span").text("Blur / Out of focus Established"); 
  });

});
</script>
</head>
<body>

<input type="text">
<br />
<span>Click in the input field </span>
</body>
</html>




You may like to try this example here.