Web Development with jQuery®

(Elliott) #1

(^68) ❘ CHAPTER 3 EVENTS


element with class name finderIconSelected, and then you remove the finderIconSelected
class name from it. You then do the same thing with the element with class name finder-
DirectoryNameSelected. Then the function selects and adds those same class names, finderIconSe-
lected and finderDirectoryNameSelected, to elements that exist inside the element that the event
fi res on. That element, the element the event fi res on, is made available within the callback function
within the object stored in the this keyword.

Attaching Other Events


jQuery’s event API provides wrapper methods for most events, but there are some events that there
are no methods for. Which events, you might ask? Events like those found in the HTML5 drag-and-
drop API, for example. There are no jQuery-provided dragstart() or drop() methods like there are
jQuery-provided click() or mouseover() methods.

For those events, you need to use the on() and off() methods, which attach event handlers to any
named event. The following example takes the script in Example 3-1.js and rewrites it to use the
on(), off(), and trigger() methods instead of the respective built-in methods for each of the events.

$(document).on(
'DOMContentLoaded',
function()
{
$('div.finderDirectory, div.finderFile').on(
'click',
function(event)
{
$('div.finderIconSelected')
.removeClass('finderIconSelected');

$('span.finderDirectoryNameSelected')
.removeClass('finderDirectoryNameSelected');

$(this).find('div.finderIcon')
.addClass('finderIconSelected');

$(this).find('div.finderDirectoryName span')
.addClass('finderDirectoryNameSelected');
}
);

$('div.finderDirectory, div.finderFile')
.filter(':first')
.trigger('click');
}
);

This example is identical in functionality to Example 3-1; you can fi nd it in the source materials as
Example 3-2.

Instead of $(document).ready(), $(document).on('DOMContentLoaded') provides identical function-
ality. You can think of jQuery’s on() method as being close to the standard addEventListener()

http://www.it-ebooks.info

Free download pdf