08 March 2013

jQuery Tutorial (Part 4) – Event Listeners



Today we’re going to kick it up a notch and really show where jQuery shines – events. If you followed the past tutorials, you should now have a fairly good understanding of the basic code structure of jQuery (and all the horrible curly braces that go with it), as well as how find elements of the DOM and some of things you can do to manipulate them. I also showed you how to access the developer console in Chrome and how you might use it to debug your jQuery code.


Events – among other uses – let you react to things that happen on the page and user interactions – clicking, scrolling, and all that fancy stuff.


What Is An Event Anyway?


For those new to programming that involves a graphical interface of some kind, events refer to any kind of interaction between the user and the application; or can be generated internally by some other process. Applications choose which events to “listen for”, and when that event is triggered, they can react in some way.


For example, tapping on your iPhone screen will generate a single “tap event” with an x,y coordinate of precisely where you tapped. If you tapped on a particular object, like a button, it’s likely that the button was listening for that event and will perform some action accordingly. If it was just a blank part of the interface, nothing was attached to the event and so nothing will happen.


Dragging your finger across the screen would generate another event, one which includes information about the start and end point of the drag movement, and perhaps the velocity. Events provide us with an easy way to react to things that happen.



Easy: Clicking


Perhaps the easiest event to listen for is the click event, fired whenever a user clicks on an element. This needn’t be a specific “button” – you can attach an event listener to anything on the screen, but as a web developer, you obviously need to make that intuitive. Creating a pseudo-button out of the letter a hidden within a paragraph of text is possible, but somewhat stupid.


The methods for attaching an event listener have changed significantly over the years as jQuery has developed, but this is the current accepted method, using on():



$(selector).on(event,action);

To listen for a “click” event on any elements with the class .clickme, and then log a message to the console containing the text of the element clicked on, you would do:



$(".clickme").on("click",function(){
console.log($(this).text());
});

You should be able to see that the action we’ve embedded here is an anonymous function which uses the this selector (which refers to whatever object jQuery is currently dealing with) – in this case, the thing that was clicked on. We then extract the text of that clicked object and log it to the console. Easy, right?


Stop The Default Action:


At some point, you’ll want to attach to something like a link or form submit button which usually does something else. In which case, it’s quite likely you don’t want that original action to be performed – instead, you want to do some fancy AJAX or special jQuery magic.


To prevent that default action from happening, we have a handy method called preventDefault. Obviously. Let’s see how that would work when dealing with a submit button for a form





$("#myForm").on("submit",function(event){
console.log(event);
event.preventDefault();
return false;
});


A few changes here – firstly, we’re attaching to the submit event instead of click. This is more appropriate when dealing with a form as the user might tab-space, hit enter, or hit a submit button – all of which would trigger the form’s default action. We’re also passing the event variable into the anonymous function, so we can refer to the event data. We’ve then used the event.preventDefault() in combination with return false to stop all the usual actions from completing.


In this case, it’s only logging the event to the console, but in reality you would probably have an AJAX handler here, which we’ll tackle in the next lesson.


Events Can Also Be Triggered By You


In the past two examples, we used the on method to listen to an event, but you can also manually trigger an event by calling it as a method instead. It’s difficult to see why you might use this to force a “click”, but makes more sense if we look at the focus event.


Focus is typically used with input fields to fire off a message when the user clicks in the box to enter text – an instructional message on the format to use, for instance. But you could also use it to force the user into the username field when the page has loaded – so they can immediately begin typing their login details.





$(document).ready(function(){
$('#username'.focus();
});


If you had also attached a focus event listener to that username field, it would also be triggered when you forced focus. Events can therefore be both triggered and listened for.



For now, practice by attaching to various events on the page – you can find a full listing of all the events available here – remember to use preventDefault if it’s a link or button, and see what output you get from the console about event data.


I’ll leave it there today as we near the end of this mini-series of jQuery tutorials. You should, by the end of it, be confident enough to throw some jQuery on your page and make it do something. Next week we’ll look at AJAX – an important part of the modern web that allows you to load and send requests in the background without interrupting the user.


As ever, feedback, questions, comments and problems welcome below, or post your questions over to our very own MakeUseOf Answers.


Image credit: Touchscreen via Shutterstock


The post jQuery Tutorial (Part 4) – Event Listeners appeared first on MakeUseOf.



No comments:

Post a Comment