Tuesday, 18 September 2012

Dojo Mouse and Keyboard Events

Keyboard events in dojo are pretty easy for the most part!  You can just use the on() function to attach them and you are done! The on function is part of the "dojo/on" module which will need to be part of the require or define declaration.

Example to catch mouse down events on a particular dom


    on(registry.byId("myDiv"), 'mousedown', function(evt){
        console.log("Mouse Down Event");
    });


Catch keyup events on an input area.


    on(registry.byId("search"), "keyup", function(evt) {                
        doSearch(registry.byId("search").get('value'));
    });


The biggest problem arises when you want to catch a keyboard event on a dom object which doesn't normally accept keyboard input such as a div, span etc.  In this case you need to make it focusable and by far the easiest way to do that is to add a tabIndex.

    dom.byId("myDiv").tabIndex = 0; // Allow key events
    on(dom.byId("myDiv"), 'keypress', function(evt){
        console.log("KeyPress Event");
    });

You can use the dojo/keys module to check for the key value just like in Java Swing.


    if (evt.keyCode == dojo.keys.LEFT_ARROW){

    } else if (evt.keyCode == dojo.keys.RIGHT_ARROW) {

    }




No comments:

Post a comment