|

jQuery Event Handling

jquery

Now that we have covered a lot of the basics with selectors and filters in jQuery, we’re ready to jump into something that’s a bit more interactive and fun. What would this be? Well it would be jQuery Event Handling of course! When using jQuery, the thing that you will do first, and most often, is selecting and filtering elements. A very close second will be working with JavaScript Event Handlers by way of jQuery. It is through event handling that we can begin to add true interactivity and dynamic behavior to our web pages.


Overview of jQuery Events

If you have done any programming in JavaScript, you’ll know that working with events is fairly straightforward. Then you test your latest creation in a different browser and find that something got broken! This is a major source of frustration and jQuery aims to simplify and help us with this process.

By combining the ability to use selectors and filters to easily capture elements on the page with the event handling features of jQuery, we are given a powerful combination. Just one mouse click can be made to trigger a series of commands like adding a class, starting an animation, changing the text on the page, or sending data to a server. Often times we’ll see the blur event used to check that form fields have been properly filled before submission.

Working with events in jQuery:

  • Gives web developers a way to work with events that is much more simplified than working directly on the DOM.
  • Makes different browser implementations of events a non issue via Abstraction.
  • Provides web developers a nice time saving technique of binding and unbinding event handlers to one or many elements by using selectors and filters all at once.

Binding Event Handlers in jQuery

The first event handler we usually learn in jQuery is the ready() event handler. We’ve talked about how events are happening all the time in our pages, and one of those events is the process of the web page actually loading. JavaScript uses the onload() method to check when the page has finished loading. It is important to know when the page is ready for interactivity so that we can begin executing any JavaScript or jQuery. If you try to run code before the document is ready, it will fail, and we don’t want that! This is why you’ll see this snippet of code in almost all jQuery applications:

You can also use the short-hand version, but I advise against it. Why? The first version, while slightly more verbose, gives you the exact indication of what it is providing when it is written. Why complicate your code any more than it needs to be? If you like, use the following snippet, but we’ll keep on using the first option here 🙂

Adding and removing event handlers to elements on the page is as easy as calling either the .on() or .off() methods in your code. There are a few ways to implement these so we’ll just whip up some code to examine how they work. Let’s look at a few different scenarios here:

jquery event handling

Oh yeah! This is pretty awesome. We have a few different applications of the .on() method, we’ll step through them one at a time.

First up we have the line of code which grabs the element with the id of #theclicker and uses .on() to attach a click event, then run the event handling function named clickster. In this style, we we pass in a named function as the event handler. We could have also just passed in an anonymous function, but sometimes the named approach is a little easier to read in the code. This way we can read it quite easily and know what action is taking place when the event is triggered. $('#theclicker').on('click', clickster); reads, “Grab #theclicker element, and when it gets clicked, run the clickster function”. We put the named functions outside of the $(document).ready(); for easier code reading.

Next up we attach the mouseover and mouseleave events to the element #mouseable. This shows an example of being able to pass in multiple events as the first argument to the .on() method. So what this second instance shows us is that any time the user mouses over, or mouses out of the element which has the id of #mouseable, they are going to trigger the mickeymouse function. All that function does is simply add a nice blue background color to one of the paragraph elements in the page. And come on, who doesn’t love Mickey Mouse?!

The third instance of this example uses the .on() method to actually bind a function which removes the event handler from the element which has the #mouseable id. If we look at the code $('#off').on('click', itsoff); it reads as follows. “Select the element with the id of #off, and when the user clicks it, run the itsoff function.” Lets examine the event handling function:

So when the itsoff function runs, it grabs the element with the id of #mouseable and uses the .off() method to remove both the mouseover and mouseleave events from triggering the mickeymouse function. Awesome, Donald Duck would be proud.

The last piece of this example is really interesting, and important to understand. We can use the .on() method as a way to peer into the future of our web page. There will often be cases where the document gets modified and elements get added dynamically after the page has loaded. So how can we deal with these newly created elements? How can we select them, or add event handlers to them? We can do this by taking advantage of the fact that events bubble in the DOM. What this means is that, when an event happens, if there is no handler for it, it will bubble up to the parent elements to see if there is a handler there. In our case, we are adding li elements dynamically as children to a ul element with the id of #backtothefuture.

Now, what if we want to take an action, or handle an event for those individual li elements that have been added to our web page after the fact? We can do this by using the .on() method on the parent element, and specifying what element(s) we want to take action on as the second parameter to the .on() method. This is how we do it:

This line of code gives a cool fade in and out effect as the user moves the mouse across any future li elements that were added. The parent element with the id of #backtothefuture acts as a container of sorts for all of the li elements that get dynamically added to the page. We use .on() method and specify 3 parameters. You likely recognize that parameter 1 is the event we want to bind and parameter 3 is the event handling function. So what then is parameter 2? Parameter 2 is a selector we specify to filter the descendants of the original selected item to determine which will trigger the event. So in this case, it says, any li elements that are descendants of #backtothefuture will trigger the anonymous function which contains the line of code $(this).fadeOut().fadeIn(); when the user mouseleaves the element. It is worth noting, that we can have multiple descendant elements, and they will all work in the same way. Go ahead and test it out! Click the ‘Click to See The Future’ button multiple times to insert multiple li elements. Then move your mouse across the collection of li elements and watch the effect it creates. Pretty cool!


The jQuery Event Object

We are in the age of modern web browsers with Google Chrome, Mozilla Firefox, Microsoft Internet Explorer, Apple Safari and others leading the way. They all work great, yet still, they do not all work exactly the same. When writing event handling code, you may still get frustrated with cross browser issues creeping up. It has in fact gotten much better than it used to be, but we still need help. jQuery provides this help with a Single Unified Event Object to tackle these challenges. Using the jQuery event object can provide a wealth of information via its properties and methods. Here is a table of the most commonly used properties and methods available in the jQuery Event Object.

Property

Use Case

type Captures what type of event occured
target What page element issued the event
data What data was passed to the bind function
pageX, pageY Document relative coordinates of the mouse when the event triggered
result Value returned from the last handler function
timeStamp The time when the event occurred

Method

Use Case

preventDefault() Prevents the Web Browser from executing the default action
isDefaultPrevented() Returns whether preventDefault() was ever called on this object
stopPropagation() Stops event bubbling to parent elements
isPropagationStopped() Returns whether stopPropagation() was ever called on this object

Having access to this information is helpful for making different applications and logic in your jQuery code. Let’s put together some code to show how we can access some of this information from the jQuery Event Object.

jquery event object

Try it out right here!

Let’s understand what is happening in this code. For our markup, we just add some various HTML elements to the page and add some basic styling to them so that we have something colorful to look at. We could just as easily have done this example with just black and white text and no styling, but what fun would that be?! With our HTML in place, we can set up our jQuery code within the ready handler of our script file. The main idea here is that when an event handling function runs in jQuery, we can pass in the event to the function and then access its properties inside of that function. Many times you’ll see jQuery written with an evt, or event, or just plain e passed into the event handling function. In our example here, we are using evt, but you can use whatever name you like to reference the jQuery Event Object so long as the name you pass in, is the one you reference inside of the event handling function. When we pass in evt, we will then access the properties of that object inside the function using things like evt.pageX, evt.pageY, evt.type, evt.target, evt.timeStamp, and so on.


Additional jQuery Event Functions

jQuery also has some additional special case type event functions for use. These might be used in certain edge cases or specific applications. Here are three of these event handlers.

$(selector).one(type, data, handler); This works the same as bind(), however the event handler is only executed one time for each matched element in the wrapped set. You can almost think of this as something like flash messages in PHP where a session message gets set but only for one page refresh.

$(selector).trigger(event, data); Triggers an event on every matched element in the wrapped set. This also causes the default action of the browser to be executed. If the click event is passed to the trigger() method, the browser will act like the item were actually clicked.

$(selector).triggerHandler(event, data); Triggers all bound event handlers on an element for a given event type without executing the browser default actions, bubbling, or live events. This event only works on the first matched element in the wrapped set.

As an example, in the prior code snippet we had set up event handlers for the page. Using .on() we bound the click event to various elements. Now, when the page loads, there is a div that remains populated with default text as you see here.

jquery trigger event

We could use the .trigger() event handler to actually trigger that click event as if a user had made the click. By doing this, as soon as the page loads, a click is triggered, and that div is populated with event object information as if someone had actually clicked a page element. It is a bit of an edge case, but you may find it useful from time to time.

We saw earlier how to use .off() to remove an event handler from a given element. You can almost think of using .one() as a shortcut to be able to set up an element to respond to an event, and then immediately remove that event handler once it has completed its task just one time.

The triggerHandler() method is probably the most esoteric of this collection of additional event handlers. The use case is if you would like to trigger an event handler in order to get access to it’s return value, but you don’t want to actually alter the DOM in any way or affect any event bubbling. Unless you know exactly how and why to use this one, it might be best to use other methods to solve your problem.