How to make a Rigger for a SEM jQuery event?

Asked

Viewed 4,681 times

5

In jQuery, when I want to make a Rigger for 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>
<button id="button">Clique em mim</button>

But it’s been a long time since I’ve used jQuery.

How can I fire (Trigger) an event WITHOUT USING JQUERY?

5 answers

9


Generating native events in native Javascript can be a headache. I remember a while ago I made a test to generate event wheel in Mootools and the function to trigger that event was 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 nowadays there’s a new API, Event, that tries to normalize this and be the same in all browsers. IE does not support, but others support.

According to this API can also be created custom-Events, ie with the name we 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>
<button id="button">Clique em mim</button>

7

Natively this should be done through the method dispatchEvent of an object EventTarget. The parameter indicated in this method should be an object of the type Event. That is, first we need to create the instance of the event we want to shoot; in this case, to illustrate, I will use the 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>

5

Another way will be using the dispatchEvent, that 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 which indicates if Event has bubble effect. Default value is false.
  • "cancelable": (Optional) Boolean which indicates if the event is cancellable. The default value is false.
  • "composed": (Optional) Boolean indicating if this event will activate other events outside of one shadow root. Default value is false.

We could thus create an object MouseEvent setting its properties before being launched:

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 on MDN

Reference to the object Event on MDN

  • The answer looks good, but in the description this composed and in the example this view, I think this is a little confusing.

  • @Guilhermenascimento Thank you for the comment. Yes indeed I left as was the example on MDN, but I agree it’s clearer without view

3

It would not just be the use of .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 definitive solution.

In this question has several other options of how to do this.

  • Yes is a shortcut and works, without having to write everything, the new Event is interesting for some configurations and/ or other types of events and even custom events. in the current case .click solves perfectly ;) +1

3

To trigger an event EventTarget.dispatchEvent():

Fires a specified Event for the Eventtarget by invoking the Specified eventlisteners, in an appropriate order. Processing normal rules (including the capturing and optional Bubbling Phase) applies to manually triggered events with dispatchEvent(). Eventtarget.dispatchEvent()

To capture an event addEventListener():

The addeventlistener() records a single event wait in a single target. The event target may be a single element in a document, the document itself, a window, or an Xmlhttprequest. addeventlistener

//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>

Browser other questions tagged

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