Trigger jQuery event with plain Javascript

Viewed 426

I know that it's not possible to handle a jQuery event with plain Javascript, but is it possible to trigger a jQuery event with plain Javascript?

Something like:

$('body').trigger('myevent', myvar);
2 Answers

Yes, as JQuery is just a library of JS:

this

$('myElem').trigger('myevent');

is equivalent to:

elem.dispatchEvent(myevent);

The question would be: why you need to mix vanilla JS and JQuery?

Is this what you want?

document.body.addEventListener('event', myFunction); // add a listener for the event

function myFunction(event) { // this function will be called when the event happens
   // handle event
}
Related