Run prototype event

Does anyone know of a way to trigger an event in Prototype, how can you use the jQuery trigger function?

I linked the event listener using the observation method, but I would also like it to be able to fire the event programmatically.

Thank you in advance

+60
javascript prototypejs events
Jan 20 '09 at 9:54
source share
4 answers

event.simulate.js fits your needs.

I have used this several times and it works like a charm. It allows you to manually trigger your own events , for example, clicking or hovering like this:

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

The great thing is that all attached event handlers will execute as if you yourself clicked on an element.

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

+84
Jan 20 '09 at 10:12
source share

I don’t think there is one built-in prototype, but you can use it (not tested, but should at least bring 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'); 
+35
Jan 20 '09 at 10:15
source share

I found this post helpful ... http://jehiah.cz/archive/firing-javascript-events-properly

It covers the way events are triggered in both Firefox and IE.

 function fireEvent(element,event){ if (document.createEventObject){ // dispatch for IE var evt = document.createEventObject(); return element.fireEvent('on'+event,evt) } else{ // dispatch for firefox + others var evt = document.createEvent("HTMLEvents"); evt.initEvent(event, true, true ); // event type,bubbling,cancelable return !element.dispatchEvent(evt); } } 
+5
Apr 20 '10 at 15:45
source share

The answers here are true for "normal" events, that is, events that are defined by the User Agent, but for custom events you must use the "fire" prototype. eg.

 $('something').observe('my:custom', function() { alert('Custom'); }); . . $('something').fire('my:custom'); // This will cause the alert to display 
+3
Jun 25 2018-11-21T00:
source share



All Articles