How do i simulate a click or keydown 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.
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.
.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?
精彩评论