OnClick button does not respond

Asked

Viewed 71 times

-1

Hello, I’m starting to study JS, I decided to make this simple page testing some features, but I don’t understand why the button "Alert!" not be returning Alert('clicked button'); from now on I appreciate any help.

Course of JS Alert!
<script>
    var btnElement = document.querySelector('button.botao');

    btnElement.onClick = function() {
       alert('Botao clicado');
    }
</script>
  • puts a Return before Alert that will work

  • https://braziljs.github.io/eloquente-javascript/chapters/manipulando-eventos/

2 answers

1

You have to use an addeventlistener to monitor the button click event, in it you pass the event type and the function that is called

1


According to @Rafael Costa’s answer "You have to use an addeventlistener to monitor the button click event, in it you pass the type of event and the function that is called".


addeventlistener(event, function[, optional]);

The first parameter is the event type (such as " click" or " mousedown" or any other HTML DOM event .)

The second parameter is the function we want to call when the event occurs.

The third parameter is optional and is well explained in this link.

Note that you do not use the prefix "on" for the event; use "click" instead of " onclick".

document.querySelector('button.botao').addEventListener("click", MarcusVinicius);

function MarcusVinicius() {
  alert("Botao clicado exemplo 1");
}
   
<button class="botao">Click me</button>

Second example

var btnElement = document.querySelector('button.botao');
                                    
btnElement.addEventListener("click", function() {
    alert('Botao clicado exemplo 2');
});
<button class="botao">Click me</button>

Third example

var btnElement= document.querySelector("button.botao"); // Acessando o botão // 
btnElement.addEventListener("click", MarcusVinicius); //chamando a função MarcusVinicius quando o evento click ocorrer //

function MarcusVinicius(){ 
alert('Botao do terceiro exemplo clicado');
};

   
<button class="botao">Click me</button>

inserir a descrição da imagem aqui

  • Mto Thanks! for sure the course I was seeing is outdated, sla, vlww ai mano.

Browser other questions tagged

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