Event Types - JS

Hi Guys,

I am currently learning about event types and I am just doing this exercise https://www.codecademy.com/paths/web-development/tracks/build-interactive-websites/modules/dom-javascript-events/lessons/dom-events/exercises/dom-event-types.

Anyway, I am trying to get past the task and somehow this piece of code doesnt do or trigger any events or anything at all '//

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
function colorChange () {
let randomColor = ‘rgb(’ + rgb(255) + ‘,’ + rgb(255) + ‘,’ + rgb(255) + ‘)’;
event.target.style.backgroundColor = randomColor;

button.onclick = colorChange();
mysteryButton.onwheel = colorChange(); ’

So the button.onclick doesnt seem work when wrap it in a regular function. However it does work like butter when the “colorChange()” function is changed into a named function expression being

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

//obviously changing the calls to
button.onclick = colorChange;
mysteryButton.onwheel = colorChange; ’

Can anyone shed some light why a regular function wont trigger anything??

Merci Beaucoup! x

This statement is assigning undefined because it invokes the function, which returns undefined (no return statement).

This statement assigns the function as a callback which is only invoked when an event triggers it.

Just noticed something else amiss…

That should throw an error.

let foo = function () {


It is important to know that when functions are written as expressions they are not hoisted so must appear in the source listing before they are assigned as callbacks. That’s the way you have it, so no problem there.


Hi Mtf,
Cheers for taking the time.

Ah…I can see it know. Thanks a lot again x

Happy Coding!

1 Like