Day # 40: Colored squares
Putting color onto elements when you are learning web development is one of the most effective techniques you can apply to acquire knowledge. It’s fun and helpful at the same time, because you will be able to practice while enjoying the process.
For today’s website I thought I could put some color onto a list of tiny squares. To achieve that, we need to create those squares by using Javascript:
for(let i = 0; i < SQUARES; i++) {
const square = document.createElement('div')
square.classList.add('square')
square.addEventListener('mouseover', () => setColor(square))
container.appendChild(square)
}
Then, we assign random colors to each square:
const colors = ['red', 'yellow', 'pink', 'green', 'magenta']
function getRandomColor() {
return colors[Math.floor(Math.random() * colors.length)]
}
And finally, we establish those colors for each square:
function setColor(element) {
const color = getRandomColor()
element.style.background = color
element.style.boxShadow = `0 0 2px ${color}, 0 0 10px ${color}`
}
Comments
Post a Comment