4

I need to simulate a click or mouse event. I tried various things but the lib i am using doesnt seem to respond to it or does respond but only on specific browsers. ATM i do $('#target').val($('#target2').val()); which works on firefox and opera. Fails on chrome, IE8 and safari.

I could add events to the libs but i wouldnt know which event to add (or how to do it properly). Anyways how do i solve this? basically i am setting the textarea text with .val() and the lib doesnt seem to pick up that event.

jAndy
  • 231,737
  • 57
  • 305
  • 359
  • What you mean by "libs"? What library? What you expect to happen when you set the textarea text? `$('#target').val($('#target2').val());` got nothing to do with click or keydown event, it's only setting value of something to be equal to value of something else.. – Shadow The GPT Wizard Jan 18 '11 at 14:21
  • @Shadow Wizard: yes and as i mention the library i am using doesnt pick up the event. I need to trigger the event for the code to work correctly –  Jan 18 '11 at 14:25
  • yes to what? You didn't answer any of my questions and none was Yes/No.. – Shadow The GPT Wizard Jan 18 '11 at 14:34

3 Answers3

3

You could use the DOM Level 2 Event Model, like:

function simulateClick(element) {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  cb.dispatchEvent(element);
}

Demo: http://www.jsfiddle.net/4yUqL/66/

This will truly simulate a mouseclick on an element. Regardless how events were bound.

jAndy
  • 231,737
  • 57
  • 305
  • 359
  • That didnt work but KeyboardEvent did :). Accepted! `var evt = document.createEvent("KeyboardEvent"); evt.initKeyboardEvent("keypress", true, true, null, false, false, false, false, 0, 0); element.dispatchEvent(evt);` –  Jan 18 '11 at 14:46
  • @qwertymk: It does for me. In all browsers except IE (8) –  Jan 18 '11 at 14:47
  • well, I'm not quite sure how many browsers this implement already. FireFox 3.6.13 works well for me. – jAndy Jan 18 '11 at 14:48
  • @qwertymk: Does this one work for you? I havent tried to make this one FF compatible. http://www.jsfiddle.net/4yUqL/71/ –  Jan 18 '11 at 15:04
  • @qwertymk: strange, the answer link works great for me. The only thing i can think of is javascript is blocked or disabled in firefox or by an addon. –  Jan 18 '11 at 23:30
2

.trigger('click') in jQuery might achieve what you're trying to do. It will fire all the handlers attached to the click event.

Robert
  • 21,110
  • 9
  • 55
  • 65
1

In case anyone bumps into this looking for a framework agnostic way to fire any HTML and Mouse event, have a look here: How to simulate a mouse click using JavaScript?

Community
  • 1
  • 1
TweeZz
  • 4,779
  • 5
  • 39
  • 53