Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create event observer for focus?

Tags:

Is it possible to have focus events bubble in protoype?

I am trying to prevent having to assign an observer on every input element.

<script language="javascript" type="text/javascript"> document.observe('dom:loaded', function() {      // Doesn't work     $('editForm').observe('focus', function(evnt){         console.log('FOCUS!');     });      // Works     $('editForm').select('INPUT').each(function(elem) {         elem.observe('focus', function(evnt){             console.log('FOCUS!');         });     });  });  </script>  <form method="post" name="editForm" id="editForm" action=""> <input type="text" name="foobar" /> </form> 
like image 674
Louis W Avatar asked May 21 '09 15:05

Louis W


People also ask

What is the difference between focus and Focusin?

The focusin event fires when an element is about to receive focus. The main difference between this event and focus is that focusin bubbles while focus does not. The opposite of focusin is focusout .

What is the difference between Blur and Focusout?

The main difference between this event and blur is that focusout bubbles while blur does not. The opposite of focusout is focusin .

What is focus in event?

The focus event fires when an element has received focus. The main difference between this event and focusin is that focusin bubbles while focus does not. The opposite of focus is blur . This event is not cancelable and does not bubble.


1 Answers

focus and blur events don't bubble.

You can fire event-handler during capturing phase. When using standard DOM methods, you would write

document.addEventListener('focus',function(e){/*some code */}, true); 

the 'true' value is here most important.

The problem is that IE doesn't support capturing phase of event propagation, but for IE you can use focusin and focusout events, which - unlike focus and blur events - do bubble. I recommend reading an article on this topic written by Peter Paul Koch. Other browsers (Firefox, Opera, Safari) probably (I didn't test it) support events like DOMFocusIn, DOMFocusOut which are equivalents for IE's focusin and focusout events.

like image 174
Rafael Avatar answered Sep 18 '22 13:09

Rafael