jeudi 26 décembre 2019

Using Event Listeners (Javascript, jQuery) to change BG color to a random color?

I am attempting a simple random background color generator. When a user clicks the button, the background color changes to a random RGB value. However, I also want the button itself to change to that random color when clicked.

I tried putting DOM manipulators in the event listener and in the random RGB function. However I keep getting this error message:

script.js:19 Uncaught TypeError: Cannot set property 'backgroundColor' of undefined
    at randomBgColor (script.js:19)
    at HTMLButtonElement.<anonymous> (script.js:7)
randomBgColor @ script.js:19
(anonymous) @ script.js:7

The code is as follows:

<html>
<button id="press" class="button">Press me to change the background color!</button>
</html>
var changeColor = document.getElementById("press");
var button = document.getElementsByClassName("button");



changeColor.addEventListener("click", function(){
    randomBgColor();

})


function randomBgColor() {
    var x = Math.floor(Math.random() * 256);
    var y = Math.floor(Math.random() * 256);
    var z = Math.floor(Math.random() * 256);
    var bgColor = 'rgb(' + x + ',' + y + ',' + z + ')';
    console.log(bgColor);
   document.body.style.background = bgColor;
   button.style.backgroundColor = bgColor;

} 



Aucun commentaire:

Enregistrer un commentaire