Your code is correct, except for the syntax error in Var
, that would be all in tiny: var
. Note the Javascript syntax, which differentiates upper-case from lower-case letters. When using Var
the program does not recognize the command and returns the error: Uncaught SyntaxError: Unexpected identifier
(it is always good to look at the console to view possible errors in the code).
On the question of adding the ()
in the assignment and trigger function Alert, it occurs because the code that comes after the assignment operator =
is executed as soon as it is read, ie when doing:
botão.onclick = alerta();
Will simply execute the function alerta()
and nothing else. It would be the same as just putting alert();
.
The onclick
calls an anonymous function this way:
botão.onclick = function(){}
How you created a function alerta()
, you can replace the block function(){}
the name of the function, without the ()
, just as you did:
botão.onclick = alerta;
This way you are assigning the function to the event onclick
, and not running it, because the variable alerta
is already a function and you are assigning it by reference.
See the difference between the two things:
alerta(); -> com parênteses: executa a função
alerta; -> sem parênteses: referencia ao valor na variável "alerta"
Now, as they said in the comments, avoid accents in variables: use botao
instead of botão
(see a topic regarding this).
use
botão.addEventListener("click", alerta);
, and avoid names with accents, try using onlybotao
– Ricardo Pontual
Ricardo Punctual, vlw man, I’ll try here!
– David Artagnan
@Davidartagnan Your logic is correct and better than the answer given. The only thing is that you put
Var
withV
uppercase. Just solve this and the code will work, but be careful when making the assignment in theonclick
anyway. Always preferaddEventListener
to avoid generating side effects on the application.– Woss