19

For JS Unit test, I need to check that a double-click behaves as expected. The issue is that the event was registered via element.addEventListener. And for some reason, in this case, element.ondblclick() does not work. HTML:

<input type="image" src="pic.jpg" id="aa"/>

Javasript:

document.getElementById('aa').addEventListener("dblclick", function(){alert('aa')});
document.getElementById('aa').ondblclick();

Fiddle: http://jsfiddle.net/prZKy/

If you double click on the image, it works, but the ondblclick() in the javascript does not work.

Anyone has an idea on how to do it?

Stilltorik
  • 1,662
  • 4
  • 19
  • 31

2 Answers2

44

You can use dispatchEvent to programatically trigger events:

var event = new MouseEvent('dblclick', {
    'view': window,
    'bubbles': true,
    'cancelable': true
  });
document.getElementById('aa').dispatchEvent(event);

See the section "Triggering built-in events" on MDN.

warren wiser
  • 57
  • 2
  • 10
CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
  • 7
    @Nenotlep Because IE9 sucks ass and doesn't recognize the `dblclick` event. You need to hack yourself a `click` handler which sets a timeout, faking a double-click. [Yuck](http://stackoverflow.com/questions/17408714/double-click-using-ie). – CodingIntrigue Jun 18 '14 at 09:14
  • how to dispatchEvent to a coords instead of getElement? – Dee Jul 07 '23 at 11:01
3

This should work:

var doubleClickEvent = document.createEvent('MouseEvents');
doubleClickEvent.initEvent('dblclick', true, true);
e.currentTarget.dispatchEvent(doubleClickEvent); // inside method
Toastrackenigma
  • 7,604
  • 4
  • 45
  • 55
Namish
  • 114
  • 1
  • 6