jQuery focus blur events

In this post I will show how this ‘focus’ and ‘blur’ events are useful to us. In the previous post the addClass and removeClass functions triggered on mouseover and mouseout events. In this example let’s see how these functions get triggered in blur and focus events.

In this example used form input field. These two functions get triggered when focus and blur the textbox.

Example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>jQuery focus and blur events</title>
<script language="javascript" src="js/jquery-1.4.1.js"></script>
<script language="javascript">
$(document).ready(function(){ // this for document in ready state

$('#domain_name').addClass("idleField");

$('#domain_name').focus(function() {
$(this).removeClass("idleField").addClass("focusField");

if (this.value == 'click here…'){
this.value = '';
}

});
$('#domain_name').blur(function() {
$(this).removeClass("focusField").addClass("idleField");
if ($.trim(this.value) == ''){
this.value = (this.defaultValue ? this.defaultValue : '');
}
});

});
</script>
<style type="text/css">
#domain_name{
padding:7px;
outline:none;

}
.focusField{
border:solid 1px #73A6FF;
-moz-box-shadow: 0 4px 18px #73A6FF;
background:#EFF5FF;
color:#000;
}
.idleField{
background:#F5F5F5;
color: #6F6F6F;
border: solid 1px #DFDFDF;
}
</style>
</head>

<body>
<div><input type="text" name="domain_name" id="domain_name" value="click here…" size="40"></div>
</body>
</html>

In the above example, the textbox having value ‘learrnwebdevelopment.info’. While focus on textbox this text will disappear and when move cursor from this textbox the blur event fire and again the textbox value is filled. The addClass and removeClass functions just for making styles.

Demo:

You can see the real time example for these functions here http://qualitypointtech.net/pagerank/index.php

Posted in jQuery