Focusing and Blurring Elements with the jQuery JavaScript Library - Using the blur() method
(Page 3 of 4 )
If you found it easy to handle focus events with the jQuery library, you'll find it extremely simple to understand how to process a “blur” action. Indeed, triggering a predefined JavaScript function when a specific element within a web page gets blurred is practically a piece of cake.
Of course, if you paid close attention to the examples developed in previous sections, then you may have already guessed that jQuery comes with a method designed specifically for handling blur events. And you’re correct! Fortunately, the library incorporates an intuitive “blur()” method, which can be easily tied to any element within a web document.
The following code sample demonstrates how to utilize this method in a concrete situation. Here it is:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Basic example on using jQuery with blur event</title>
<style type="text/css">
body{
padding: 0;
margin: 0;
background: #fff;
}
h1{
font: 24px bold Arial, Helvetica, sans-serif;
color:#000;
}
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("a").blur(function(){
alert('Redirecting to Devshed.com now!');
});
});
</script>
</head>
<body>
<h1>Basic example on using jQuery with blur event</h1>
<a href="http://www.devshed.com/">Visit Devshed.com now!</a>
</body>
</html>
After analyzing closely the above hands-on example, you’ll have to agree with me that handling blur events with the jQuery framework is actually a no-brainer process that can be tackled with minor efforts. As you can see from the prior code sample, the blur() method has been tied to a link that points to “Devshed.com.” This means that when this element gets blurred for whatever reason, it will pop up an alert box on screen before performing the redirection process. That certainly wasn’t too hard to grasp, right?
At this point, you hopefully understand how to process a simple blur event with jQuery. I think it's time, therefore, to explore other useful characteristics of the library.
In the last section of this article, I’m going to explain how to build a primitive JavaScript application that detects the submission of web forms. You've probably done this tens, even hundreds of times before.
However, in this specific case, this common task will be performed via the API provided by jQuery, so if you’re interested in learning how this will be done, please jump ahead and read the following section. It’s only one click away.
Next: Introducing the submit() method >>
More JavaScript Articles
More By Alejandro Gervasio