I am in the process of learning JS and I constantly have feeling that my code is bloat and not optimal.
I built this simple DEMO of background changing on click. Can somebody tell me if this is good approach to build this, what can be improved? Can I write this with less code?
HTML
<div id="one">
<div id="two"></div>
</div>
CSS
div {
width: 200px;
height: 200px;
border: 1px solid dimgrey;
display: flex;
margin: auto;
transition: background-color .4s ease-out;
}
div > div {
width: 100px;
height: 100px;
border: 1px solid darkgray;
}
JS
var divOne = document.getElementById("one"),
divTwo = document.getElementById("two"),
divOneStyle = divOne.style,
divTwoStyle = divTwo.style,
RGB = ["red","green","blue"],
YPB = ["yellow","purple","black"];
var colorMeRGB = function (event) {
divOneStyle.backgroundColor = RGB[Math.floor(Math.random() * RGB.length)];
event.stopPropagation();
};
divOne.addEventListener("click",colorMeRGB,false);
var colorMeYPB = function (event) {
divTwoStyle.backgroundColor = YPB[Math.floor(Math.random() * YPB.length)];
event.stopPropagation();
};
divTwo.addEventListener("click",colorMeYPB,false);