Last Updated: February 25, 2016
·
2.227K
· ihcsim

Create And Trigger OnKeyDown Events In QUnit

I was looking for a way to simulate "onkeydown" events in my QUnit tests. The answer lies in the JQuery Event object (http://api.jquery.com/category/events/event-object/).

 // create and trigger onkeydown events
$(this).bind("OnUpArrowKeyDown", 
            onUpArrowKeyDownEventHandler);
var upArrowKeyEvent = jQuery.Event("OnUpArrowKeyDown", 
    {keyCode: 38});
$(this).trigger(upArrowKeyEvent);

function onUpArrowKeyDownEventHandler(event) {
    if(event.keyCode == 38)
        ; // do something
}

For more examples on creating custom events with parameters, refer http://jsfiddle.net/ivan_sim/hWKYf/.

For a list of complete keyboard keycodes, refer http://www.webonweboff.com/tips/js/event_key_codes.aspx.