14

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

Trevor Rudolph
  • 1,055
  • 4
  • 18
  • 42

2 Answers2

29

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.

  • That's one of the few snippets around that worked for me in Safari/Chrome. Thanks! – auco Apr 14 '12 at 23:35
  • Thanks. But it doesn't work (mobile Safari). Is there any possibiity to send an event for global document? – Dmitry Aug 09 '12 at 13:30
  • In my case works only the second part of the code but with `eventObj.keyCode = key;`! Mobile Safari 5.1. – Dmitry Aug 09 '12 at 14:12
0

How are you simulating the event? document.dispatchEvent doesn't work in all browsers. You can test the feature using this: typeOf(document.dispatchEvent) != 'undefined'

SavoryBytes
  • 35,571
  • 4
  • 52
  • 61