Execute code inside Event Listener

Asked

Viewed 121 times

1

Hello! How do I execute a code inside the event listener programmatically?

Example:

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

I want to execute the alert of addEventListener. I tried to name function(), and call alerta_listener() but it didn’t work.

2 answers

1

You can run the alert (or any other code within the event listener) 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>

0


You can abstract the content of this function, and create another, calling it when you want. 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 Trigger.

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

Browser other questions tagged

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