HTML5 and CSS3, Second Edition

(singke) #1
On line 3, we use event.target to get a reference to the actual element the user
clicked on. We can then wrap that with a jQuery object to work with it. This
works even if we dynamically add new elements to this region.

Sometimes we need to be more specific about the events we watch, so we
could define the event handler on the parent, but specify exactly what elements
the event should apply to, like this:

links.on("click","a",function(event){
element= $(this);
// morecode
});

In this case we pass the selector as the second argument to on(). We get the
same effect, but this gives us more flexibility; if we had a container with lots
of elements and different events to watch, this method would let us easily
make those connections, whereas simply looking for clicks on the parent
element would catch all click events and bubble them up.

The Original Event


When we use any of the jQuery event functions like on() or click(), jQuery wraps
the JavaScript event in its own object and makes only some of the properties
available on the wrapper object. Sometimes we need to get to the actual event
so we can access the properties that didn’t get mapped. jQuery events give
us access to the original event with the appropriately named originalEvent
property. We can access the data property of the onmessage event like this:

$(window).on("message",function(event){
varmessage_data= event.originalEvent.data;
});

You can use this technique to call any of the original event’s properties or methods.

A2.6 Document Ready


The phrase “unobtrusive JavaScript” refers to JavaScript that’s kept completely
separate from the content. Instead of adding onclick attributes to our HTML ele-
ments, we use event handlers like we just explored in Section A2.5, Events, on
page 267. We unobtrusively add behavior to our document without modifying the
document itself.

One drawback to this method is that JavaScript can’t “see” any of the elements
in our document until they’ve been declared. If we loaded our JavaScript code
inside the <head> section of the document, the JavaScript code would be immedi-
ately executed and none of the elements we want to interact with would be
available to us because they haven’t been rendered by the browser yet.

report erratum • discuss

Document Ready • 269


Download from Wow! eBook <www.wowebook.com>

Free download pdf