Execute Event.observer inside other different event (with prototype)

/ Published in: JavaScript
Save to your folder(s)

I've found a very nice (and standard) solution to firing events while it's not normally available, this piece of code searchs the active element (a text input) inside the Event.observers collection and fires the "onchange" event (normally not possible in explorer) when the return key is pressed.

- this code requires prototype.js -

Hope you enjoy it!

Copy this code and paste it in your HTML
  1. $A(document.getElementsByClassName('text', $('main-form'))).each(function(poElement){
  2. Event.observe(poElement, 'change', function(e){
  3. // this event only fires while tabbing after changing content
  4. Element.addClassName(poElement, 'changed');
  5. }, false);
  7. Event.observe(poElement, 'keypress', function(e){
  8. var cKeyCode = e.keyCode || e.which;
  10. if (cKeyCode == Event.KEY_RETURN){
  11. // but now will fire also while pressing return key
  12. Event.observers.findAll(function(poEventObserver){
  13. return poEventObserver[0] == poElement && poEventObserver[1] == "change";
  14. })[0][2]();
  15. }
  16. }, false);
  17. });

Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.