Simulate left and right arrow key event with javascript

Trevor Rudolph picture Trevor Rudolph · Apr 1, 2011 · Viewed 23.4k times · Source

I'm using the slide.html5rocks.com framework and I'm trying to use to img tags inside of a tag links and I can't get the JavaScript onclick to simulate the left and right key events to change slides

Answer

user1385191 picture user1385191 · Apr 1, 2011

You're looking for something that will dispatch an event. Here's something that should work:

function fireKey(el)
{
    //Set key to corresponding code. This one is set to the left arrow key.
    var key = 37;
    if(document.createEventObject)
    {
        var eventObj = document.createEventObject();
        eventObj.keyCode = key;
        el.fireEvent("onkeydown", eventObj);   
    }else if(document.createEvent)
    {
        var eventObj = document.createEvent("Events");
        eventObj.initEvent("keydown", true, true);
        eventObj.which = key;
        el.dispatchEvent(eventObj);
    }
} 

I made a cool little interface test with it that will probably interest you. Here's how it looks: http://jsfiddle.net/FvCut/6/

Tested as working in Firefox 3.6, Opera 11, Safari 5, IE 8, and IE 7/IE Quirks Mode. Of note: Opera 11 doesn't fire repeated "keydown" events when you hold a key down like most browsers.