JavaScript Interactive Websites Chore Door

In this exercise, why does botDoorPath have to be declared as a global variable rather than block scoped?
Thanks

anyone got an idea on what this could be?

If it is block scoped then it is not available to other functions. All the images and listeners (and handlers) need to be globally scoped.

Sorry what’s a handler? I thought listeners (.onclick) and handlers were the same thing? Or is listener literally the .onclick part and the handler is the function that follows, telling the browser what to do?

Secondly, in this example, I wanted to change the doorImage1 src from default to the botDoorPath image. Since I only want this image to show when clicking occurs, why does it need to be globally scoped?

Like If I wasn’t going to reference the botDoorPath src again, why does it even matter?

As a general rule of thumb, can I just memorise that images should always be global scoped?

Thanks!

They work hand in hand but they are not the same thing. Listeners are like a switchboard operator who takes all the calls and directs them to the worker who can handle the call.

Listeners listen; handlers handle.

When we declare a listener we add to the attribute list of the element we call it on.

element.onclick = handlerFunction;

The attribute is set to the callback reference. You’ll see this written as registering an event listener or some such (at least in my writing). The act of registering adds the attribute to the element node in the DOM.

Events are a very busy part of the background activity of JavaScript. The keyboard, the mouse, the touchscreen, and the namespace itself are all constantly being polled for events in their respective context. Some functions signal when they’re done; the mouse pointer signals any movement, wheel motion, button click; the keyboard signals any key movement; the touchscreen signals any contact or gesture.

When an event is detected the script engine races through the DOM and tracks down any nodes with a matching event type attribute and assigns it to the target node, which the handler can now act upon, or traverse away from as a point of reference to a neighboring element.

The polling takes place probably 60 or more times per second. The global Event object gets populated with new data after any event. It’s that object that in the example script is passed to the handler function. I called it e.

Click Run and mouse over the two boxes.

1 Like

Sorry for the delayed response, but it makes perfect sense. Thanks so much for the response and brilliant answer!

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.