Deeper understanding of event handler callback (Event types RGB random button color exercise)

I am on this exercise:

This is the complete code when I finished: (it works)

// This variable stores the "Pick a Color" button
let button = document.getElementById('color-button');

// This variable stores the "Mystery Color" button
let mysteryButton = document.getElementById('next-button');

// This random number function that will creates color codes for the randomColor variable
function rgb(num) {
  return Math.floor(Math.random() * num);

// Write your code below
let colorChange = function (event) {
  let randomColor = 'rgb(' + rgb(255) + ',' + rgb(255) + ',' + rgb(255) + ')'; = randomColor;

button.onclick = colorChange;

mysteryButton.onwheel = colorChange;

The point fo the code is, if either of 2 buttons are triggered it will change either button’s background color to a random hue.

So, near the bottom of the code, an onclick event on the ‘button’ will perform a callback on the function colorChange.
Then, that callback function creates a randomColor value and assigns it to the event’s target.

for onclick, the MDN website says: The function receives a mouse event object as its sole argument.

So, regarding: let colorChange = function (event) {
is button.onclick = colorChange; sending a parameter ‘event’ to the callback function?

MDN says this argument is an object. What information does this object contain?

I’m just trying to understand this logic as fully as possible.

Also, could the line have been written as:
let colorChange = function (anyName) { ,
as long as the statement inside was written as: = randomColor;` , correct?

And, finally, could the callback function have been defined using the => shorthand?
i.e. let colorChange = (event) => { ?

Thanks so much,


Yes. It is the global object, event which among its properties has a target attribute that is bound to the DOM node that received the click.

The object has a few dozen attributes. Event type is the one that matches to the click event, above. It also has all the details about the mouse, keyboard and other input devices, and methods to help with stuff like setting CSS style, etc.

We could try to write some script to let us inspect the object. Create a page with one button, and write the listener and handler. A ‘Button Clicked’ response is all we need to write back to the screen.

Also in the handler make a copy of the EventObject.

const eventObject = event    // ???
const code = document.createElement('code')
const text = document.createTextNode(eventObject)

Not tested, but you get the gist. Do this on your own machine.

Thank you for all of that. It helped clear up some things in my mind.

1 Like