HTML and CSS Reference
In-Depth Information
As expected, an anonymous function has no name. It's completely anonymous and can't
be called from other code segments. Look at the following example:
window.onload = function () {
}
This example is used throughout the topic to ensure that the page is fully loaded before
accessing elements in the DOM; otherwise, the elements wouldn't be available. The onload
event for the window object is being assigned an anonymous function. This function doesn't
have a name and can't be called by any other code. The inner implementation of the window
object runs this function when raising the onload event.
In JavaScript, functions are objects that can be assigned to variables. This is how the
anonymous function event listener works. It assigns a function object to the onload property
of the window object, which in turn handles the event when the window is completely loaded.
You can use anonymous functions in most cases where a function is expected as a parameter
also. Take the following code sample:
window.addEventListener("load",
function () {
document.getElementById("outer").addEventListener("click", outerDivClick, false);},
false);
In this sample, the addEventListener method is used. But instead of passing in the func-
tion name to call when the event is triggered, an anonymous function is passed in. The only
potential problem with this approach is the ability to later remove the event listener with the
removeEventListener method. That the following code would work might seem logical:
window.removeEventListener("load",
function () {
document.getElementById("outer").addEventListener("click", outerDivClick, false); },
false);
But this isn't the case. Because the event listeners that the addEventListener method adds are
stored by their signatures, this removeEventHandler method can't know the signature of the
previous anonymous function. Even passing in the exact same anonymous implementation
doesn't work because this isn't the same anonymous function; it's a new one and therefore
doesn't match the signature of the added one.
Canceling an event
The ability to cancel event processing can be useful when you want to completely over-
ride the implementation of the native functionality of a DOM element. A perfect example
is if it was required to override the inherent functionality of an anchor element. An event
listener would be set up for the click event. Then in the click event, via the event object, the
 
Search WWH ::




Custom Search