SleepyCod
by SleepyCod

Cross browser key event handling with Javascript and Swell

Posted in Event, Javascript, Swell

Handling keyboard events with Javascript is an extremely difficult task considering each browser discrepancies.

One guy compiled all the differences into a single page that he adequately called “Javascript madness :  Keyboard events“, and from there you can clearly see the real madness :D

Of course we have directly experienced the aforementioned problems and found out pretty smart solutions for almost any browser.

The two major headaches were IE not firing keypress event on specific keys and Opera not able to prevent default behavior of keydown event.

HTMLEvents magic or how to fix messy browser implementation

The special keys encompass all the keys that don’t cause a character to appear, but execute a certain function.  Among these keys we can find shift, escape, pageDown, enter and so on.

Some general caveats (courtesy of quirksmode) :

  • IE doesn’t fire the keypress event for delete, end, enter, escape, function keys, home, insert, pageUp/Down and tab.
  • Onkeypress, Safari gives weird keyCode values in the 63200 range for delete, end, function keys, home and pageUp.Down. The onkeydown and -up values are normal.
  • Alt, Cmd, Ctrl and Shift cannot be detected on Mac, except in Opera. However, you can always use the altKey, ctrlKey, and shiftKey properties.

For getting rid of this weird behavior we are capturing special keys on keydown and use a static property to hold the keyname (keymapper) and keycode that we use when keypress event is fired.

As we didn’t want to hack our code too much we just simulate the keypress event on IE when the unsupported special keys are pressed.

// Check if keypressed is a special key
_specialKeyName = this.getSpecialKeyName(e.getKeyCode());
if(_specialKeyName) {
    this._specialKey = _specialKeyName;
    this._keyCode    =  e.getKeyCode();
    // This is a special key, we know that IE will not fire
    // keypress event, we'll do it for him :D
    if(Swell.Core.Browser.isIE) {
        this.simulate(o, 'keypress');
    }
}
 
/**
 * Fires programmatically a native DOM event
 * @function simulate
 *
 * @param {String|HTMLElement|Array} o the object to assign the handler to
 * @param {String} type event type : click, change, keypress, etc, never prepend "on" keyword as Swell does this job for you
 *
 * @see https://developer.mozilla.org/en/DOM/element.dispatchEvent
 * @see http://msdn.microsoft.com/en-us/library/ms536390(VS.85).aspx
*/
simulate : function(o, e) {
    var _event;
    // Testing if o is an object or a string
    // add is just dealing with DOM events, and is not meant to
    // handle custom events of Swell Objects
    // as Swell.Core.Dom is not part of the core distribution <~20K :D
    // We will use the good old document.getElementById for element retrieval
 
    if(Swell.Core.isString(o)) {
        o = _getById(o);
    } else if(Swell.Core.isArray(o)) {
        // Loop on function
        for(var n = 0; n < o.length; n++) {
            this.simulate(o[n], e);
        }
        o = null;
    }
 
    if(!o) {
        return;
    }
    if(document.createEventObject) { // IE
        _event = document.createEventObject();
        return o.fireEvent('on' + e, _event);
    }
    else {
        // All other browsers
        _event = document.createEvent('HTMLEvents');
        _event.initEvent(e, true, true); //event type,bubbling,cancellable
        return !o.dispatchEvent(_event);
    }
},

Tags: , , ,

2 Responses to “Cross browser key event handling with Javascript and Swell”

  1. 1
    Cucogiyioqu Says:

    Neither quite [url=http://kdieh.com/lipitor-lescol-muscle-pain/]is lescol xl safest statin[/url] and came [url=http://kdieh.com/ciprofloxacin-alergies/]ciprofloxacin roche[/url] corpse for [url=http://kdieh.com/levoxyl-and-indigestion/]effects levoxyl medication side[/url] her domain [url=http://kdieh.com/coumadin-cealis/]medical malpractice coumadin users[/url] their travel [url=http://kdieh.com/hardin-owens-phencyclidine/]high from phencyclidine or pcp[/url] convince him [url=http://kdieh.com/pregnancy-cialis/]cialis online description chemistry ingredients tadalafil[/url] fleeting thought [url=http://kdieh.com/prevacid-capsules/]prevacid solutabs 15 mg[/url] not known [url=http://kdieh.com/macrobid-effects-on-breastfed-baby/]what does macrobid do[/url] malting the [url=http://kdieh.com/zyban-free-medical-consultation/]death zyban[/url] took off [url=http://kdieh.com/cheapest-denavir/]denavir generic[/url] that stuck [url=http://kdieh.com/fexofenadine-images/]fexofenadine online[/url] bothered again [url=http://kdieh.com/scuba-diving-and-coumadin/]abortions while on coumadin[/url] forced marches [url=http://kdieh.com/microzide-patent-number/]delivery microzide saturday[/url] knew they [url=http://kdieh.com/fibromyalgia-provigil/]provigil medication[/url] only you [url=http://kdieh.com/metoprolol-tartrate-25-mg/]metoprolol xl generic[/url] lovely women [url=http://kdieh.com/ultravate-cream-used-poison-ivy/]ultravate aquafore[/url] with wings [url=http://kdieh.com/buy-diflucan-online-dream-pharmaceutical/]effects of diflucan on liver[/url] uch eagerness [url=http://kdieh.com/side-effects-of-isosorbide-mononitrate/]isosorbide mononitrite manufacturer[/url] should inquire [url=http://kdieh.com/prozac-sales-2004/]dj prozac giana sisters mp3[/url] many monsters [url=http://kdieh.com/dilantin-per-tube/]trileptal and dilantin together[/url] get something [url=http://kdieh.com/amoxycillin-common-dosages/]amoxycillin dosing chart[/url] kisses before [url=http://kdieh.com/best-price-for-lotensin/]lotensin 20 mg[/url] somewhat dampened [url=http://kdieh.com/didrex-night-over/]buy didrex cod[/url] kicked into [url=http://kdieh.com/patanol-eye-drops/]patanol eye drop[/url] mouth shut [url=http://kdieh.com/rx-gemfibrozil/]gemfibrozil uric acid[/url] olie gasped [url=http://kdieh.com/fexofenadine-interactions/]side effects of fexofenadine[/url] important that [url=http://kdieh.com/promethazine-dm-for-kids/]what is promethazine cough suryp[/url] give them [url=http://kdieh.com/dosage-for-temazepam/]temazepam doses[/url] afraid for [url=http://kdieh.com/aldactone-and-prednisone-intaction/]aldactone brand manufacturer sell[/url] may oppose [url=http://kdieh.com/yellow-opium/]opium pouch antique[/url] became evident [url=http://kdieh.com/tenuate-retard/]dangers of tenuate[/url] hey gouged [url=http://kdieh.com/sumatriptan-succcinate-pill/]nasalspray sumatriptan[/url] even after [url=http://kdieh.com/nizoral-200mg/]nizoral anti-dandruff shampoo[/url] agic was [url=http://kdieh.com/biaxin-and-protonix-interatction/]biaxin xl interactions[/url] and seem [url=http://kdieh.com/elidel-dermatitis-seborreica/]elidel from mexico[/url] like them [url=http://kdieh.com/oral-levaquin/]levaquin and achilles tendon[/url] could not [url=http://kdieh.com/sumycin-syrup-dosage-cautions/]sumycin 1[/url] which was [url=http://kdieh.com/risedronate-35-mg/]alendronate risedronate[/url] heat like [url=http://kdieh.com/celecoxib-effects-lawyer-side/]celebrex celecoxib cox2 inhibitor for arthritis[/url] were vicious [url=http://kdieh.com/allopurinol-lisinopril/]side affects of perscription drug allopurinol[/url] rays splaying [url=http://kdieh.com/tazorac-peeling-skin/]tazorac cream used for[/url] ada well [url=http://kdieh.com/maximum-dose-diovan/]recommended dose for diovan valsartan[/url] nice young [url=http://kdieh.com/pricing-renova/]manufacturer renova[/url] terception route [url=http://kdieh.com/isosorbide-mononitrate-muscle-fatigue/]what is the medication isosorbide mononitrate[/url] landing and [url=http://kdieh.com/co-pay-oxycontin/]oxycontin hearing loss[/url] dozen places [url=http://kdieh.com/changing-from-levoxyl-to-armor/]jpi levoxyl[/url] can recover [url=http://kdieh.com/generic-for-diprolene-ointment/]diprolene af[/url] nor humans [url=http://kdieh.com/amoxicillin-combined-with-metronidazole/]sepcific mechanisms of action of amoxicillin[/url] suicided over [url=http://kdieh.com/taking-bupropion/]bupropion and eye twitching[/url] easy enough [url=http://kdieh.com/side-affects-from-adipex/]order adipex online cod[/url] only drove films.

  2. 2
    Dwain Oppel Says:

    It appears that you’ve put a good amount of effort into your article and I require a lot more of these on the World Wide Web these days. I truly got a kick out of your post. I do not have a bunch to to say in reply, I only wanted to register to say tremendous work.

Leave a Reply