Events

One of the beauties of jQuery is the ability to easily add event handlers, which are methods that are called only upon a specific event or action taking place. For example, the method of adding a class to an element can be set to only occur upon that element being clicked on.

Below is a standard selector, grabbing all of the list items. The .click() event method is bound to the list item selector, setting up an action to take place upon clicking any list item. Inside the .click() event method is a function, which ensures any actions inside the event method are to be executed. The parentheses directly after the function are available to pass in parameters for the function, in which the event object is used in this example.

Inside of the function is another selector with the .addClass() method bound to it. Now, when a list item is click that list item, via the this keyword, received the class of saved-item.

$('li').click(function(event){
  $(this).addClass('saved-item');
});

Event Flexibility

The .click() event method, along with a handful of other event methods, is actually a shorthand method which uses the .on() method introduced in jQuery 1.7. The .on() method provides quite a bit of flexibility, using automatic delegation for elements that get added to the page dynamically.

Making use of the .on() method the first argument should be the native event name while the second argument should be the event handler function. Looking at the example from before, the .on() method is called in place of the .click() method. Now the click event name is passed in as the first argument inside the .on() method with the event handler function staying the same as before.

$('li').on('click', function(event){
  $(this).addClass('saved-item');
});

Nesting Events

It is possible to have multiple event handlers and triggers, nesting one inside another. As an example, below the .on() event method is passed the hover argument, thus being called when hovering over any element with the class of pagination. Upon calling the .on() event the .click() event is called on the anchor with the up ID.

$('.pagination').on('hover', function(event){
  $('a#up').click();
});

Event Demo

Using an alert message as a demo, the following code snippets show how to create an alert message and then removing that message based upon clicking the close icon.

HTML
   <div class="alert-warning">
      <strong> Warning! </strong>
      Best check yo self, youre not looking too good.
      <div class="alert-close">×</div>
   </div>

JAVASCRIPT
   $('.alert-close').on('click', function(event){
     $('.alert-warning').remove();
   });
Demo of above code
Warning! Best check yo self, you're not looking too good.

comments powered by Disqus