Javascript error

Asked

Viewed 32 times

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 ?

  • 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')

1 answer

1


The error is in ' btnElement.onclick = createQuaded() ', so you are indicating that the function should already be immediately executed, when in fact it should only be executed when the button is clicked. The following code should work for you.

var btnElement = document.querySelector('button#btn');
var boxApp = document.querySelector('div#app');

btnElement.onclick = function criarQuadrados(){
    var quadrado = document.createElement('div');
    quadrado.style.width = '100px';
    quadrado.style.height = '100px';
    quadrado.style.backgroundColor = '#F00';
    boxApp.appendChild(quadrado);
}
  • Really solved my problem, but now I have another doubt, I did this way "btnElement.onclick = createdQuadrados;" and it worked too, but I found it strange he recognize a function and I did not put the parentheses to indicate that it is a function.

  • 1

    In javascript almost everything is an object, when passing only the name of the function, you will be passing the content of that object, already you pass the name of the function with the parentheses, you will be indicating that the function has to be executed at that moment when the code is being interpreted. I don’t know if it’s clear, but that’s it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.