Focuser //JavaScript Repository

Description

Extends elements that are unable to receive focus, allowing them to handle the following events: keypress, keydown, keyup, blur and focus.
Created: 2006.02.14 - Modified 2013.09.17

Dependencies

Code (Download)

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/geral/focuser [rev. #3]

focuser = function(o){
    var x, $ = document.body.appendChild(document.createElement("input")), s = $.style,
    h = function(e){(o["on" + e.type] instanceof Function) && o["on" + e.type].call(o, e.key);};
    $.type = "text", s.position = "absolute", s.left = s.top = "-100px";
    o.blur = function(){$.blur();}, addEvent(o, "click", o.focus = function(){$.focus();});
    for(x in {keypress: 0, keydown: 0, keyup: 0, blur: 0, focus: 0}) addEvent($, x, h);
};

Example (Example)

<style type="text/css">
#type{
    background: #eef;
    border: 2px inset #999;
    overflow: auto;
    padding: 30px;
    margin: 30px;
    width: 200px;
}
</style>

<div id="type">
<b>Click and type to edit</b> the &lt;div&gt;. Press TAB or click "out" to test the focus.
<i>The objective of this example isn't to edit, but test the "focus" and "key" events.</i>
</div>

<script type="text/javascript">
//<![CDATA[

var t = document.getElementById("type");
focuser(t);
t.onfocus = function(){
    this.style.background = "#fee";
};
t.onblur = function(){
    this.style.background = "#eef";
};
t.onkeypress = function(k){
    var s = this.innerHTML;
    this.innerHTML = k == 8 ? s.slice(0, -1) : s + String.fromCharCode(k);
};

//]]>
</script>

Help

focuser(object: HTMLElement): void
Turns the field focusable.
object
reference element
After the function calling, the element will be enhanced with the following events and properties:

Events

Element.onkeypress: Function(key: Integer): void
Occurs when the key is pressed, can be called several times while the key is pressed.
key
code of the pressed key
Element.onkeydown: Function(key: Integer): void
Occurs when a key is pressed.
key
code of the pressed key
Element.onkeyup: Function(key: Integer): void
Occurs when a key is released.
key
code of the pressed key
Element.onfocus: Function(void): void
Occurs when the element receive focus.
Element.onblur: Function(void): void
Occurs when the element loose focus.

Methods

Element.focus(void): void
Focus the element.
Element.blur(void): void
Removes the focus of the element.

Rank (Votes: 18)

3.22