The description is very confusing, but as far as I can see, it is asking you to change the background colour of the colour input. Although it says button, it isn’t actually asking you to define a button.
When you attach an event listener, that function takes a parameter that represents the event that occured – this is an object with a load of useful information. You don’t need to use getElementById
here because the event itself will have a reference to the thing the event occurred on – it’s stored as the target
property.
function changecolor(event /* this is the object that gets populated. when the input is clicked */) {
// THIS IS THE ELEMENT THAT CAUSED THE EVENT:
console.log(event.target)
// THIS IS THE VALUE OF THE INPUT AFTER THE CLICK:
console.log(event.target.value)
}
Secondly, and maybe counterintuitively, the click event will not work as you expect. If you attach the function to to onclick
, and you wire it up properly, what will happen is that the background colour will only visibly change the next time you click:
- Initially, there is no value, so…
- Click on the input – this is when the event occurs, and the value is currently not defined
- This sets the background colour to undefined
- The colour picker opens
- Pick a colour (say green) from the colour picker and close the picker
So the background colour has not visually changed, even though you’ve picked a colour. So:
- Click on the input – this is when the event occurs, and the value is whatever was just picked in the last steps (green)
- Background colour changes to green
- The colour picker opens
- Pick the colour from the colour picker (say blue) and close the picker
…And the background colour is still green, you need to click it again to make it change to blue. And so on.
To have it change when the colour is picked, you need to use either oninput
or onchange
(instead of onclick
) to listen to the input
or change
events respectively:
-
input
will make the background change whenever anything changes in the input (this is the best in terms of visual feedback for the user) .
-
change
will make the background change when the user closes the colour picker.
Either of these are more relevant to the problem that the click
event.
Lastly, you should really be attaching the listeners in the JavaScript, using addEventListener
rather than using the inline on{eventname}
attributes in the HTML, but can look at that after you get something working.