Jump to content
Larry Ullman's Book Forums

Chapter 8 Page 293

Recommended Posts

Hi all,


I have just completed chapter 8 of the book and came across something I don't quite understand. In chapter 8 page 293 we make a new function call setHandlers and have an array of events in string format named events. In step 6, the code loops through the array and calls the following code:


var checkbox = U.$(events);


If I'm not wrong the U.$ is a function in a global object that returns the element for the passed in Id (the code in my U.$ function after checking for type string is return document.getElementById(id)). Now later in step 7 the code checks if the checkbox is checked like so:


if (checkbox.checked) etc.


Now after reading some materials online, I still don't understand how it is we can get a reference to the checkbox by passing in the name of an event to the U.$ method. Everywhere where I have read, the method accepts only the name of an element, so how is it that when we pass in an event name say 'mouseover', that we get a reference to the checkbox, so we can check if it is checked etc.


I'm new to Javascript, so if I've made a mistake in the above explanation, I apologise.


Thank you all in advance.

Link to comment
Share on other sites

You have to look at the HTML for this script to really get the full picture.

If you download the scripts for the book, in the ch08 folder is a file named "events.html".

If you look at the IDs of the checkbox inputs, then you'll notice that they all match the strings in the events array.

Said slightly differently, the strings in the events array correspond to the IDs of each of the checkboxes.

As such, by using the document.getElementById method on those strings, you will get a DOM object that corresponds to each of the checkbox inputs.


Given the above, each time through the loop, a DOM object corresponding to the checkbox element with the corresponding ID is stored in the variable "checkbox", and then that element is checked to see whether it is checked or not.

If the checkbox has been checked, then the corresponding event is set up for the document object. Otherwise, the event (if it was previously set up) is removed.


That make sense?

  • Upvote 2
Link to comment
Share on other sites

Yes it does!


Cheers HartleySan, I don't use the scripts for the book, I write the html out myself to practise. It didn't occur to me to check the html, I guess that's why I have the "newbie" on my user :)


Thanks for the quick reply.

Link to comment
Share on other sites


  • Create New...