Friday, January 4, 2013

How to make a div to receive focus event

Jest a little tip this time:
Focus doesn't work on div tags by default. But, according to jquery documentation:

The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (, , etc.) and links (). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.
So, in order to make focus work on a div you should add 'tabindex' attribute to it. Here follows example:
<!doctype html>
<html lang="eng">
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
   <style> body div { width: 300px; height: 300px; border: solid 1px black; }   </style>
   <body>
      <div id="output">text text text input</div><br/>
      <input type="text">
      <script type="text/javascript">
         $(document).ready(function () {
            var output = $('#output'); 
            output.attr('tabindex', -1);
            output.bind('focus', function() {
               console.log('Got focus event from div!');
            });
            output.bind('blur', function() {
               console.log('Got blur event from div!');
            });
         });
      </script>
   </body>
</html>
And here follows output of the example:
Got focus event from div!
Got blur event from div!
Got focus event from div!
Got blur event from div!
Got focus event from div!
Got blur event from div!
Got focus event from div!
Got blur event from div!