Run code inside the event listener

1

Hello! How do I run a code within event listener programatically?

Example:

document.getElementById("voltar").addEventListener('click', function() {
    alert("teste");
}, true);

I want to execute alert of addEventListener . I tried to set a name in function() , and call alerta_listener() but it did not work.

    
asked by anonymous 03.11.2017 / 19:42

2 answers

0

You can abstract the contents of this function, and create another by calling it at any time. Ex:

 function Teste(){
    alert("teste");
}

document.getElementById("voltar").addEventListener('click', function() {
  Teste();
}, true);
<button type="button" id="voltar">Voltar</button>

Or, if you use JQuery, you can trigger the event using the trigger .

Ex: $(elemento).trigger("click");

    
03.11.2017 / 19:46
1

You can run alert (or any other code within event listener ) by creating a trigger click() for the event:

document.getElementById("voltar").click();

document.getElementById("voltar").addEventListener('click', function() {
    alert("teste");
}, true);

document.getElementById("voltar").click();
<input type="button" value="Voltar" id="voltar" />

You can also use a separate function:

function alerta(){
    alert("teste");
}

document.getElementById("voltar").addEventListener('click', alerta, true);

function alerta(){
	alert("teste");
}

document.getElementById("voltar").addEventListener('click', alerta, true);
<button type="button" id="voltar">Voltar</button>
    
03.11.2017 / 21:07