Intro to JS- Handle to Button Click

by Jacktea

HTML

<button id="myButton">Click Me</button>

<div id="myBox"></div>

CSS

#myBox {
    position: absolute;
    width: 100%;
    height: 100%;
    z-index: -1;
    background: brown; 
    top:0; <!-- allows for it to fill entire space, rather than just be a floating object-->
    left:0;
}

JavaScript

var myButton = document.getElementById("myButton");

var handleClick = function() {

    //this is the local function scope of "myBox"
    var myBox= document.getElementById("myBox");
    
    myBox.style.background=getRandomColor();
};

//get random color function
var getRandomColor = function() {
    var r = Math.ceil(Math.random() * 255);
    var g = Math.ceil(Math.random() * 255);
    var b = Math.ceil(Math.random() * 255);
    
    var rgbValue = "rgb(" + r + "," + g + "," + b + ")";
    
    //css color style format -> rgb(255,255,255);
    
    //console.log(rgbValue);
    
    return rgbValue;
}

console.log(myBox); //this is the global scope "myBox"

myButton.addEventListener("click", handleClick);