Event target Syntax

Hey all - I had a question about a little nuance in event handler function syntax. See below code for randomizing a button color

// This variable stores the "Pick a Color" button
let button = document.getElementById('color-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) + ')';
  event.target.style.backgroundColor = randomColor;
}

button.onclick = colorChange;

Specifically looking at

let colorChange = function (event) {
  let randomColor = 'rgb(' + rgb(255) + ',' + rgb(255) + ',' + rgb(255) + ')';
  event.target.style.backgroundColor = randomColor;
}

button.onclick = colorChange;

I’ve always thought that when a function has an argument passed through (in this case, event) that when you eventually call that function, you would pass that event through at the end of the function. So why wouldn’t you call the event with something like

button.onclick = colorChange(button);

We must call rgb() with a number value like rgb(255) - so why not the colorChange function?

Thanks!

That is a good question ;). Please refer to the following discussion with a similar question ;).

Feel free to ask if you still have questions.