Search code examples
javascriptjquerywebkitkeydownkeyevent

Create KeyEvent in Javascript


I have the following problem - I'm catching a key event an I need to create a new altered key event(since it seems the keyCode property is read-only) and afterwards handle the newly created KeyEvent. I came across several old posts in StackOverflow where similar situations are handled, but:

  • I need this to be working under Webkit /there's a solution here in StackOverfow but it is working only in Gecko/

  • I need to create another KeyEvent, but not TextInputEvent, since the TextInputEvent will only let my specify a string to be inserted, whilst I cannot do that as I use a third party tool that needs to handle this event and I need a keycode.

  • I tried jQuery#trigger() but it won't work for me. My code is as follows

    var event = jQuery.event('keydown');
    event.which = 13; //I'm trying to simulate an enter
    $('iframe').contents().find('document').find('body').trigger(event); //my content is inside an iframe
    

Solution

  • (function($){
        $(window).load(function(){
    
            var e = $.Event("keydown");
            e.which = 13;
            e.keyCode = 13;
            $('iframe').contents().find('html, body').trigger(e);
    
        });
    })(jQuery);