Focuser //Javascript function
Extends elements unable to receive focus, allowing them to handle the following events: keypress, keydown, keyup, blur e focus.
[UPDATED CODE AND HELP CAN BE FOUND HERE]
1 2 //======================================================== 3 // REQUIRES http://www.jsfromhell.com/geral/event-listener 4 //======================================================== 5 6 //+ Jonas Raoni Soares Silva 7 //@ http://jsfromhell.com/geral/focuser [v1.0] 8 9 focuser = function(o){ //v1.0 10 var x, $ = document.body.appendChild(document.createElement("input")), s = $.style, 11 h = function(e){(o["on" + e.type] instanceof Function) && o["on" + e.type].call(o, (e.which + 1 || e.keyCode + 1) - 1 || 0);}; 12 $.type = "text", s.position = "absolute", s.left = s.top = "-100px"; 13 o.blur = function(){$.blur();}, addEvent(o, "click", o.focus = function(){$.focus();}); 14 for(x in {keypress: 0, keydown: 0, keyup: 0, blur: 0, focus: 0}) $["on" + x] = h; 15 };
Example:
1 2 <style type="text/css"> 3 #type{ 4 background: #eef; 5 border: 2px inset #999; 6 overflow: auto; 7 padding: 30px; 8 margin: 30px; 9 width: 200px; 10 } 11 </style> 12 13 <div id="type"> 14 <b>Click and type to edit</b> the <div>. Press TAB or click out to test the focus. 15 </div> 16 17 <script type="text/javascript"> 18 var t = document.getElementById("type"); 19 focuser(t); 20 t.onfocus = function(){ 21 this.style.background = "#fee"; 22 }; 23 t.onblur = function(){ 24 this.style.background = "#eef"; 25 }; 26 t.onkeypress = function(k){ 27 var s = this.innerHTML; 28 this.innerHTML = k == 8 ? s.slice(0, -1) : s + String.fromCharCode(k); 29 }; 30 </script>