Search code examples
eventskeyboardmootools

map keyboard keys with mootools


I am looking to make the enter key behave exactly like the tab key on a form.

I am stuck on the fireEvent section.

var inputs = $$('input, textarea');
    $each(inputs,function(el,i) {
    el.addEvent('keypress',function(e) {
    if(e.key == 'enter') {
        e.stop();
        el.fireEvent('keypress','tab');
    }
    });
});

How do I fire a keypress event with a specified key? Any help would be greatly appreciated.


Solution

  • this will work but it relies on dom order and not tabindex

    var inputs = $$('input,textarea');
    
    inputs.each(function(el,i){
        el.addEvent('keypress',function(e) {
            if(e.key == 'enter'){
                e.stop();
                var next = inputs[i+1];
                if (next){ 
                    next.focus();
                }
                else {
                    // inputs[0].focus(); or form.submit() etc.
                }
            }
        });
    });
    

    additionally, textarea enter capture? why, it's multiline... anyway, to do it at keyboard level, look at Syn. https://github.com/bitovi/syn

    the above will fail with hidden elements (you can filter) and disabled elements etc. you get the idea, though - focus(). not sure what it will do on input[type=radio|checkbox|range] etc.

    p.s. your code won't work because .fireEvent() will only call the bound event handler, not actually create the event for you.