admin管理员组

文章数量:1333630

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.

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.

Share Improve this question edited Jan 18, 2011 at 14:28 jAndy 236k57 gold badges312 silver badges363 bronze badges asked Jan 18, 2011 at 14:15 user34537user34537 3
  • 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 Wizzard Commented Jan 18, 2011 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 – user34537 Commented Jan 18, 2011 at 14:25
  • yes to what? You didn't answer any of my questions and none was Yes/No.. – Shadow Wizzard Commented Jan 18, 2011 at 14:34
Add a ment  | 

3 Answers 3

Reset to default 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/4yUqL/66/

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

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

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?

本文标签: javascriptHow do i simulate a click or keydown eventStack Overflow