1
People, I am a beginner in javascript and I am trying to do an exercise that consists in creating a button that generates stacked squares every time it is clicked. The point is, I’ve been over this code several times and I can’t find the error. And also my button is always automatically triggered every time the page loads. I need to understand why this happens
var btnElement = document.querySelector('button#btn');
var boxApp = document.querySelector('div#app');
//console.log(btnElement);
//console.log(boxApp);
btnElement.onclick = criarQuadrados();
function criarQuadrados(){
var quadrado = document.createElement('div');
quadrado.style.width = '100px';
quadrado.style.height = '100px';
quadrado.style.backgroundColor = '#F00';
boxApp.appendChild(quadrado);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<title>Exercicio 01</title>
</head>
<body>
<button id="btn">Clique em mim</button>
<div id = "app"></div>
<script type="text/javascript" src="js/javascript.js"></script>
</body>
</html>
so that solved the problem kkkk but I didn’t understand, creatQuadrados is a function, I didn’t have to call her using parentheses ?
– Gabriel
To understand about the function, see this question: About (Function(){ ... }()) and callThis() read the answer given by Sergio. In case I mosquei here and it is not necessary to change the selectors:
('button#btn')
and('div#app')
– NoobSaibot