
In my previous article I looked at interacting with the keyboard using JavaScript to detect key masks and combinations of key masks and normal keys. In that article I also attached the keyup event to a specific DOM element. In this article I will look at creating what is known as a special jQuery event and then attach that event to our entire document as apposed to a single DOM element.
Of course you are still able to attach this special event to a specific DOM element as well. Without further a due let’s get started. I am continuing on from my previous post so you will need some of the code from that article to follow along here. Below however, I am repeating the base HTML you will need:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>JavaScript Keyboard Interaction</title>
<script type="text/javascript" src="lib/jquery/jquery-1.3.2.js"></script>
<script type="text/javascript" src="js/keyCodeMatcher.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
<h1>JavaScript Keyboard Interaction</h1>
<p>Once you start typing in the text area below pressing Ctrl + Shift + S will save the form data to the server. With focus anywhere pressing Alt + I will load the first four images tagged with monkey from Flickr. To remove the images use Alt + C</p>
<p id="images"></p>
<form method="post" id="edit-form" action="dummy.html">
<fieldset>
<legend>Your Life's Story</legend>
<textarea rows="10" cols="40" name="content" id="content-box"></textarea><br />
<input type="submit" id="save_button" value="Save And Continue" />
</fieldset>
</form>
</body>
</html>
The Special Event
The jQuery special event allows you to create an extension to the default Event object and in our case we are going to use this to create a special event that listens for the Alt key. A special event consists of a setup, teardown and handler function. Let’s first look at the setup and teardown functions:
jQuery.event.special.alt = {
setup: function(data, namespaces) {
var elem = this, $elem = jQuery(elem);
$elem.bind('keyup', jQuery.event.special.alt.handler);
},
teardown: function(namespaces) {
var elem = this, $elem = jQuery(elem);
$elem.unbind('keyup', jQuery.event.special.alt.handler);
}
}
This is pretty much the default way that every special event will start. In the setup method we bind a specific event to the element and specify the handler that will be called to handle this event. In the teardown, we do the opposite by unbinding our event from the element. The meat lies in the handler:
handler: function(event) {
if(event.altKey) {
event.type = "alt";
jQuery.event.handle.apply(this, arguments);
}
}
The code for our special event handler is pretty straight forward but let’s run over it quickly. As mentioned earlier we want to listen for the Alt key mask so we add a conditional if statement in the handler to test for this event. If the event was triggered we set the event.type jQuery attribute to ‘alt’ and then we let jQuery handle the triggering of the alt key events.
Using Our Special Event
Now that we have our special event we can use it to add some functionality to our page. If you look at the HTML code from before, you will that there is an empty paragraph tag with an id of images. This will be the container we will interact with.
Our first step is to bind our special event to the document:
$(document).ready(function() {
$(document).bind('alt', function(event) {
}
});
With the above in place all Alt key presses will be caught by our special event and handled appropriately. At the moment it will do absolutely nothing, let’s change that. Inside the above bind statement add the following:
keyPressed = "alt" + getKey(event);
if(keyPressed.toLowerCase() == "alti") {
$("#images").append("Loading images....");
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=monkey&tagmode=any&format=json&jsoncallback=?", flickr);
}
Because we know that we are only trapping Alt key events inside this block we do not need to use the getKeyMask method from before or do any conditional statements to determine which key mask was pressed. All we need to do is append the key that was pressed in combination with the Alt and then check whether the combination we are listening for was pressed.
Currently we are listening for the Alt + i combination. This will trigger an Ajax call to the Flickr site and pass the JSON returned to the callback handler method ‘flickr’. Here is our callback method:
var flickr = function(data) {
$("#images").empty();
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("#images");
if ( i == 3 ) return false;
});
}
The combination of all of this will simply do the Ajax call and add the first four images from the response to the images paragraph mentioned above. Go ahead and give it a try in the browser. To round out this article, let’s use the special event again to listen for another key mask/key combination to clear the images.
Add the following to the bind code block after the Alt+i code block:
if(keyPressed.toLowerCase() == "altc") {
clear();
}
And then add the following for our clear method:
var clear = function() {
$("#images").empty();
}
That is it! Now when you load all of this in the browser you will be able to trigger the Ajax call and loading off the images by pressing Alt+i and clear the images again by pressing Alt+c. Special events really open the door to even more possibilities then ever before. Have fun exploring this further and I can definitely suggest the article by Brandon Aaron for further reading. Looking forward to your comments and reading how you are using jQuery’s special events.
December 19, 2009
Easily, the post is really the greatest on this worthy topic. I agree with your conclusions and will thirstily look forward to your future updates. Just saying thanks will not just be enough, for the tremendous clarity in your writing. I will directly grab your rss feed to stay privy of any updates. Gratifying work and much success in your business enterprise!
December 20, 2009
Thank you for your kind words. I am glad to hear that you enjoyed the post and could take something away from it.