Jump to content
Larry Ullman's Book Forums

Chapter 8 Questions


Recommended Posts

The events.js exercise in Chapter8 uses a nodeName property of the (e) object and I'm not sure where it comes from. Is this a user-defined property?

 

 

function reportEvent(e) {

'use strict';

 

// Get the event object:

if (typeof e == 'undefined') e = window.event;

 

// Get the event target:

var target = e.target || e.srcElement;

 

// Establish the output message:

var msg = target.nodeName + ': ' + e.type + '\n';

 

// Add the output to the textarea:

U.$('output').value += msg;

 

} // End of reportEvent() function.

 

Also, in the same exercise, a setHandler function is created that determines the events to listen for.

The utility function addEvent, to add an event is called. The addEvent function takes 3 arguments, the object, the type of event for the object and a supporting function call as the third argument.

 

 

function setHandlers() {

'use strict';

 

// List of possible events:

var events = ['mouseover', 'mouseout', 'click', 'keypress', 'blur'];

 

// Add or remove event handlers accordingly:

for (var i = 0, count = events.length; i < count; i++) {

var checkbox = U.$(events); // Get the element.

if (checkbox.checked) { // Is it checked?

U.addEvent(document, events, reportEvent);

} else {

U.removeEvent(document, events, reportEvent);

}

 

My question is this:

the document object is passed as the argument and I was wondering why the form object could not be passed since all the elements fall within the domain of the form. I tried this and it doesn't seem to work.

 

Chris

Link to comment
Share on other sites

Here are my answers:

 

1) nodeName is a predefined JS property that is part of the target property of the Event object. (It's not a user-defined property.)

 

2) The document object is passed to the functions because the form element is not the only element within the document. The document element refers to the entire document and contains the body element as well. If, for example, you active the click event and then click somewhere outside of the form, you will notice that the onclick event will still fire and report that the body element was clicked on. This would not happen if you had attached the onclick event handler to only the form.

 

If you wanted to though, you could attach the event handlers to only the form. In order to do that though, you need to properly pass a DOM object reference to the form element to the functions. There are two easy ways to do this:

 

document.forms[0]

or

U.$('theForm')

 

Hope that helps.

  • Upvote 1
Link to comment
Share on other sites

 Share

×
×
  • Create New...