user965297
user965297

Reputation: 41

How to programmatically fire ondblclick event in javascript?

I am trying the following simple code (in html, using js on IE8):

<input type="image" src="pic.jpg" id="aa" ondblclick="alert('aa');"/>
<script>
document.getElementById('aa').dblclick(); 
</script>

and I get an error that: object doesn't support this property or method (regarding the script part). And I don't get the alert.

Whereas when I dblclick on the image, I get the alert message. So I wish to know how to programmatically fire the dblclick event (without actually double clicking the image).

The same works just fine with onclick (instead of on dblclick). I also tried it on button, input text. Same error .

Upvotes: 4

Views: 5034

Answers (3)

JaredPar
JaredPar

Reputation: 754545

The property name is ondblclick but you're attempting to call dblclick. You need to call ondblclick.

<script>
  document.getElementById('aa').ondblclick(); 
</script>

Fiddle: http://jsfiddle.net/frwpY/

Upvotes: 7

Ilia Choly
Ilia Choly

Reputation: 18557

try this:

<input type="image" src="pic.jpg" id="aa" ondblclick="alert('aa');"/>
<script>
document.getElementById('aa').ondblclick(); 
</script>

http://jsfiddle.net/dnUZY/1/

Upvotes: 2

Chad
Chad

Reputation: 19609

Check out MDNs article about element.dispatchEvent

Sample code from MDN:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var cb = document.getElementById("checkbox"); 
  var canceled = !cb.dispatchEvent(evt);
  if(canceled) {
    // A handler called preventDefault
    alert("canceled");
  } else {
    // None of the handlers called preventDefault
    alert("not canceled");
  }
}

This way you can also track the event through the DOM bubble and make sure it wasn't canceled.

Upvotes: 0

Related Questions