Events in Javascript from html or from script

0

I have a question about JavaScript events. What would be the difference between doing this:

   <script>
   function mostrarMensaje(){
alert("Hola mensaje desde funcion!");
      }
   </script>
   <input id="clickeable" type="button" value="Hacé click"  onclick="mostrarMensaje()"/>

And this?

 <input id="clickeable" type="button" value="Hacé click">
 <script>
  var target = document.querySelector("#clickeable");
  target.addEventListener('click', mostrarMensaje);

   function mostrarMensaje(){
alert("Hola mensaje desde funcion!");
      }
   </script>
    
asked by Raul 11.05.2018 в 08:28
source

2 answers

2

All browsers accept the assignment of onclick as inline property, but you can trigger a single event using that property. If you use target.addEventListener instead you can add as many listeners as you want.

If you use onclick and in addition addEventListener , all will be triggered in sequence.

You can also overwrite the onclick property by doing target.onclick=mostrarMensaje .

function mostrarMensaje(msg){
  alert(msg);
}
function saluda(){
  alert('hola');
}
function despidete(){
  alert('hasta luego');
}

document.querySelector('#saluda').addEventListener('click', saluda);
document.querySelector('#saluda').addEventListener('click', despidete);

document.querySelector('#debiera').onclick=saluda;
<input id="clickeable" type="button" value="Muestra Mensaje"  onclick="mostrarMensaje('mensaje')"/>
 
 <input id="saluda" type="button" value="Mensaje, Saludo y Despedida"  onclick="mostrarMensaje('mensaje')"/>
 
  <input id="debiera" type="button" value="Saludo sobreescribe Mensaje"  onclick="mostrarMensaje('mensaje')"/>

The only drawback of addEventListener is that it is not supported in Explorer 8.

    
answered by 11.05.2018 в 13:53
1

In reality there is no difference in functionality, both do the same, but if it is recommended and it is also a good practice, do it by script, since at the moment you want to change the name to the function you have to change it at least two sites, otherwise from the script you change everything you need without touching html.

Not to mention that you have to load the function of the script before the html where the call is onClick, the ideal is to have all the javscript at the end of the page and not distributed in the middle of the code, simple organization.

    
answered by 11.05.2018 в 09:19