I have a button that when clicked, it creates a square on the screen, which is a div 100x100, like red background. For each click to appear a new square, I used container.appendChild(clone)
being var clone = quadrado.cloneNode(true)
.
The button fulfills what is expected of it, the problem happens when I create a quadrado.addEventListener('click', novaCor, false)
. Clicking on the square does not perform any function. Try to make a fiddle to show, but my button did not work on either JsFiddle or CodePen.
Follow JS:
var botao = document.createElement('button', 'clique')
var txtBotao = document.createTextNode('Clique')
var newColor = getRandomColor()
var quadrado = document.createElement('div')
var container = document.querySelector('div')
botao.appendChild(txtBotao)
botao.addEventListener('click', adicionaQuadrado, false)
quadrado.addEventListener('click', novaCor, false)
container.appendChild(botao)
quadrado.style.margin = 10
quadrado.style.width = 100
quadrado.style.height = 100
quadrado.style.backgroundColor = '#f00'
function adicionaQuadrado () {
var clone = quadrado.cloneNode(true)
container.appendChild(clone)
console.log(clone)
}
function novaCor () {
quadrado.style.backgroundColor = newColor
}
function getRandomColor () {
var letters = '0123456789ABCDEF'
var color = '#'
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)]
}
return color
}