JavaScript Events Worksheet

Questions

Question 1

What is an 'event handler'?

An 'event handler' is a function that is invoked when a certain event occurs.

For Example: btn1.onclick = function(){console.log("You clicked the button!");};

Question 2

How are event handlers invoked?

Event handlers are invoked automatically when the event occurs.

For Example: If using the example from above, when the mouse clicks on the object specified (element with the ID attribute of "btn1"), the event will occur (the console log will show "You clicked the button!").

Question 3

What is an 'anonymous' function?

An anonymous function is a function without a name. They are meant for a specific one-time use and are not reused throughout the code.

Question 4

Explain what the addEventListener() method of a DOM element is, and explain the purpose of each of it's parameters.

Every element object has a method called addEventListener() - this is another way for hooking up event handlers.

For Example: btn1.addEventListener("click", function(){console.log("You clicked the button!")});

Within the parentheses of addEventListener():
The first parameter is a string, which is the name of the event you want to listen for. The on (for example, from onclick) is omitted when using addEventListener().
The second parameter is a function, which is the event handler that will be invoked when the browser detects the event. (1) the event we are listening for (2) function // omit the 'on' - not needed for addEventListener

Coding Problems

Coding Problems - See the 'script' tag below this h3 tag. You will have to write some JavaScript code in it.

Always test your work! Check the console log to make sure there are no errors.

Orange

Green