Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger an event with Prototype

Does anybody know of a method to trigger an event in Prototype, as you can with jQuery's trigger function?

I have bound an event listener using the observe method, but I would also like to be able to fire the event programatically.

Thanks in advance

like image 262
Neil Aitken Avatar asked Jan 20 '09 09:01

Neil Aitken


People also ask

How do you trigger an input event?

Use the dispatchEvent Method querySelector('input'); element. addEventListener('change', () => console. log('change')) const event = new Event('change'); element. dispatchEvent(event);

Can JavaScript trigger events?

HTML events are handled by JavaScript. When an event occurs, it requires some action to be taken. This action can be accomplished through JavaScript event handlers. In addition to JavaScript, jQuery which is equivalent to JavaScript in terms of functionality can also be used to trigger events in a HTML document.

What is trigger event in jQuery?

The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.


2 Answers

event.simulate.js fits your needs.

I've used this several times and it works like a charm. It allows you to manually trigger native events, such as click or hover like so:

$('foo').simulate('click'); 

The great thing about this is that all attached event handlers will still be executed, just as if you would have clicked the element yourself.

For custom events you can use the standard prototype method Event.fire().

like image 72
Aron Rotteveel Avatar answered Sep 18 '22 22:09

Aron Rotteveel


I don't think there is one built in to Prototype, but you can use this (not tested but should at least get you in the right direction):

Element.prototype.triggerEvent = function(eventName) {     if (document.createEvent)     {         var evt = document.createEvent('HTMLEvents');         evt.initEvent(eventName, true, true);          return this.dispatchEvent(evt);     }      if (this.fireEvent)         return this.fireEvent('on' + eventName); }  $('foo').triggerEvent('mouseover'); 
like image 23
Greg Avatar answered Sep 18 '22 22:09

Greg