How to trigger a jQuery SEM event?

3

In jQuery, when I want to trigger an existing event, I do so:

$(function (){

  $('#button').on('click', function () {
    console.log('olá mundo');
  });
  $('#button').trigger('click');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><buttonid="button">Clique em mim</button>

But it's been a while since I've used jQuery.

How can I trigger an event without using JQUERY?

    
asked by anonymous 06.10.2017 / 15:00

5 answers

7

Generating native events in native JavaScript can be a headache. I remember a time ago doing a test for generate event wheel in MooTools and the function to trigger this event looks like this:

	function dispatchFakeWheel(type, wheelDirection){

		var event;
		try {
			// Firefox
			event = document.createEvent('MouseEvents');
			event.initMouseEvent(type, true, true, window, 120, 0, 0, 0, 0, 0, 0, 0, 0, 0, null);
			attachProperties(event, wheelDirection);
			window.dispatchEvent(event);
		} catch (e){}

		try {
			// Chrome, PhantomJS, Safari
			event = document.createEvent('WheelEvent');
			event.initMouseEvent(type, 0, 100, window, 0, 0, 0, 0, null, null, null, null);
			attachProperties(event, wheelDirection);
			window.dispatchEvent(event);
		} catch (e){}

		try {
			// IE9
			event = document.createEvent('HTMLEvents');
			event.initEvent(type, true, false);
			attachProperties(event, wheelDirection);
			window.dispatchEvent(event);
		} catch (e){}

		try {
			// IE10+, Safari
			event = document.createEvent('MouseEvents');
			event.initEvent(type, true, true);
			attachProperties(event, wheelDirection);
			window.dispatchEvent(event);
		} catch (e){}

		try {
			// IE8
			event = document.createEventObject();
			document.documentElement.fireEvent(type, event);
		} catch (e){}
	}

But today there's a new API, Event , which tries normalize this and be the same in all browsers. IE does not support, but others support.

According to this API you can also create custom-events, that is, with whatever name you want. Example:

const btn = document.querySelector('button');

function handler(e){
console.log(e.type, e.isTrusted);
}
btn.addEventListener('click', handler);
btn.addEventListener('meu-super-evento', handler);

var evt = new Event("click", {
  "bubbles": true,
  "cancelable": false
});
btn.dispatchEvent(evt); // evento click simulado

var evt = new Event("meu-super-evento", {
  "bubbles": true,
  "cancelable": false
});
btn.dispatchEvent(evt); // evento meu-super-evento
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><buttonid="button">Clique em mim</button>
    
06.10.2017 / 15:26
5

Natively this should be done using the dispatchEvent method of a object EventTarget . The parameter specified in this method should be an object of type Event . That is, we first need to create the instance of the event we want to fire; In this case, for example, I'll use events click and mouseover .

const click = new Event("click");
const mouseOver = new Event("mouseover");

We look for the target element in the DOM:

const button = document.getElementById("button");

And we trigger the respective events:

button.dispatchEvent(click);
button.dispatchEvent(mouseOver);

See working:

const click = new Event("click");
const mouseOver = new Event("mouseover");
const button = document.getElementById("button");

button.addEventListener("click", function (event) {
	alert("Click");
});

button.addEventListener("mouseover", function (event) {
	this.style.color = "red";
});

button.dispatchEvent(click);
button.dispatchEvent(mouseOver);
<button id="button">Clique em mim</button>
    
06.10.2017 / 15:26
4

Would not it be just using .click() ?

function Hello() {
  console.log('olá mundo');
}

document.getElementById('button').click();
<button id="button" onclick="Hello()">Clique em mim</button>

See also compatibility before adopting a final solution.

This question has several other options on how to do this.

    
06.10.2017 / 15:10
4

Another way is to use dispatchEvent , which implies previously creating the object that represents the event.

const botao = document.getElementById("button");

botao.addEventListener('click', function() {
  console.log('olá mundo');
});


let evento = new Event('click'); //criar o evento para o click

botao.dispatchEvent(evento); //lançar o evento criado
<button id="button">Clique em mim</button>

The event can be configured at the level of some properties:

  • "bubbles": (Optional) Boolean indicating whether the event has a bubble effect. The default value is false.
  • "cancelable": (Optional) Boolean indicating whether the event is cancelable. The default value is false.
  • "composed": (Optional) Boolean indicating whether this event will activate other events outside of a shadow root . The default value is false.

We could thus create a MouseEvent object by configuring its properties before launching:

const botao = document.getElementById("button");

botao.addEventListener('click', function() {
  console.log('olá mundo');
});


let evento = new MouseEvent('click', { /*agora MouseEvent*/
    'bubbles': true,
    'cancelable': true
});

botao.dispatchEvent(evento); //lançar o evento
<button id="button">Clique em mim</button>

Reference for Manual Event Creation in MDN

Reference for object Event in MDN

    
06.10.2017 / 15:23
2
___ erkimt ___ How to trigger a jQuery SEM event? ______ qstntxt ___

In jQuery, when I want to trigger an existing event, I do so:

//Atribuo o elemento a variável btn
var btn = document.getElementById('btn');

//Crio um evento novo chamado Clicado
var event = new Event('Clicado');

//Criar uma função para executar quando evento clicado for capturado
btn.addEventListener("Clicado", function(){
  console.log("o evento clicado foi disparado!!");
}, false);

//Dispara o evento
btn.dispatchEvent(event);

//IE e browsers em versões antigos utilizam o fireEvent
//btn.fireEvent("on" + event.eventType, event);
<button id="btn">Botão</button>

But it's been a while since I've used jQuery.

How can I trigger an event without using JQUERY?

    
______ azszpr243901 ___

Generating native events in native JavaScript can be a headache. I remember a time ago doing a test for generate event EventTarget.dispatchEvent() in MooTools and the function to trigger this event looks like this:

//Atribuo o elemento a variável btn
var btn = document.getElementById('btn');

//Crio um evento novo chamado Clicado
var event = new Event('Clicado');

//Criar uma função para executar quando evento clicado for capturado
btn.addEventListener("Clicado", function(){
  console.log("o evento clicado foi disparado!!");
}, false);

//Dispara o evento
btn.dispatchEvent(event);

//IE e browsers em versões antigos utilizam o fireEvent
//btn.fireEvent("on" + event.eventType, event);

But today there's a new API, Event , which tries normalize this and be the same in all browsers. IE does not support, but others support.

According to this API you can also create custom-events, that is, with whatever name you want. Example:

<button id="btn">Botão</button>
%pre%
    
______ azszpr243902 ___

Natively this should be done using the addEventListener() method of a object %code% . The parameter specified in this method should be an object of type %code% . That is, we first need to create the instance of the event we want to fire; In this case, for example, I'll use events %code% and %code% .

%pre%

We look for the target element in the DOM:

%pre%

And we trigger the respective events:

%pre%

See working:

%pre% %pre%
    
______ azszpr243890 ___

Would not it be just using %code% ?

%pre% %pre%

See also compatibility before adopting a final solution.

This question has several other options on how to do this.

    
______ azszpr243896 ___

Another way is to use %code% , which implies previously creating the object that represents the event.

%pre% %pre%

The event can be configured at the level of some properties:

  • "bubbles": (Optional) Boolean indicating whether the event has a bubble effect. The default value is false.
  • "cancelable": (Optional) Boolean indicating whether the event is cancelable. The default value is false.
  • "composed": (Optional) Boolean indicating whether this event will activate other events outside of a shadow root . The default value is false.

We could thus create a %code% object by configuring its properties before launching:

%pre% %pre%

Reference for Manual Event Creation in MDN

Reference for object %code% in MDN

    
______ ___ azszpr243892

To trigger an event %code% :

  

Triggers an Event for the specified EventTarget, invoking the   Specified eventListeners, in an appropriate order. Processing   normal of the rules (including the capturing and optional bubbling   phase) applies to manually triggered events with dispatchEvent ().    EventTarget.dispatchEvent ()

To capture an event %code% :

  

addEventListener () records a single event wait on a single   target. The target of the event can be a single element in a document, the   document itself, a window, or an XMLHttpRequest.    addEventListener

%pre% %pre%
    
___
06.10.2017 / 15:17