Intro to JS - Handle Button Click
by mmansion
HTML
<button id="myButton">Click Me</button>
<div id="myBox"></div>
CSS
#myBox {
position: absolute;
width: 100%;
height: 100%;
z-index: -1;
background: orange;
top: 0;
left: 0;
}
JavaScript
var myButton = document.getElementById('myButton');
var myBox = "Something different";
var handleClick = function() {
//this is the local function scope of "myBox"
var myBox = document.getElementById('myBox');
myBox.style.background = getRandomColor();
};
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);