Using only JavaScript, I want to create five nested divs. When clicking one of them, I want that only that div's background to change its color (according to an array of colors).
My problem here is that, because the divs are nested, clicking on any one of them will just color the largest one (the parent). The rest of the code is okay because if I struggle to click on a border, I can actually achieve what I want. But the idea is to work when clicking inside of the smaller div.
var currentParent = document.body;
var colors = ['red', 'black', 'green', 'pink', 'purple']
var divArray = []
for (let i = 0; i < 5; i++) {
let currentDiv = document.createElement("div")
currentDiv.style.width = `${(i * 10 + 20)}px`
currentDiv.style.height = `${(i * 10 + 20)}px`
currentDiv.position = i
currentParent.append(currentDiv)
divArray.push(currentDiv)
currentParent = currentDiv
}
for (let i = 0; i < 5; i++) {
divArray[i].onclick = function() {
this.style.backgroundColor = colors [this.position]
}
}
event.stopPropagation, and learn about event "bubbling". See e.g. javascript.info/bubbling-and-capturing