Apr
22
Simulating mouse clicks in JavaScript
Filed Under JavaScript, Programming
There might
be times when you would like to simulate a mouse click on an DOM Node and don’t know how (for instance, submitting a form when in multi-frame environment).
Furthermore, it would be nice if the functionality could extend the DOM, so as to be able to use it combined with other pre-existing features.
Here’s the script bellow, just added and use it as you please (Ex. document.getElementById(”my_element”).click();)
HTMLElement.prototype.click = function() {
var evt = this.ownerDocument.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
}
}
The code above is for Firefox only. For IE, just call document.getElementById(”my_element”).click() - it works by default, out of the box.
Quick code explanation:
- Extend/create the click function for the HTMLElement
- Create e new Mouse Event. The ownerDocument property returns the root element (document object) for a node. The createEvent arguments can be: “UIEvents”, “MouseEvents”, “MutationEvents”, and “HTMLEvents”.
- Ok, here you would normally have an initEvent, instead of initMouseEvent. The initEvent can take as parameters the name of the event, a boolean specifying whether or not the event can bubble (there are two phases, capture and bubble) and a boolean specifying whether or not the event’s default action can be prevented. The initMouseEvent can hold some other parameters (beside the ones from above), which you can check out here: initMouseEvent.
- Dispatches the event into the implementations event model.
For a nice guide of firing events (cross-browser wise), you can checkout firing javascript events properly, where there are some nice examples to think of.
Just to give a short receipt from Jehiah’s post:
function fireEvent(element,event){
if (document.createEventObject){
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
}
else{
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
Comments
21 Responses to “Simulating mouse clicks in JavaScript”
Leave a Reply








Very cool! I really like your syntax. I’ve made something similar for testing purposes for JavaScriptMVC. It simulates key events and mouse drags. You might find its code usefull if you expand your functionality.
Thanks for the comment. Will definitely dig into it as the time allows it.
I tried the same code snippet with select element its not working can you give some inputs regarding that.
Hi Venkatesh!
Sorry for responding so late, just returned from Oslo. So, I didn’t understand your question, what exactly is not working? The first code snippet is for Firefox only, so, to include it in your scripts yous should first check if the current browser is from the Mozilla family, then include it.
Hi I tried this snippet but havent got it to work. Well as per my needs, I am using a button which when clicks opens a file dialog which is a hidden field. So this is all I need to do. This works fine in IE but in Firefox it is not working fine. What do I do?
My code is:
function onBrowseClick()
{
var fileBrowser = document.getElementById(”");
var fileName = document.getElementById(”");
var ie = (navigator.appName.indexOf(”Internet Explorer”) !=-1) ? true: false;
if(!ie)
{
alert(”inside firefox”);
HTMLElement.prototype.click = function() {
var evt = this.ownerDocument.createEvent(’MouseEvents’);
evt.initMouseEvent(’click’, true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
}
}
else{
fileBrowser.click();
}
fileName.value = fileBrowser.value;
}
How I do get fileBrowser.click() to work in firefox? Thanks…would appreciate urgent help.
I am using firefox 3.o
Hi Calvin!
Sorry for the late answer, I’m on a different time zone here. So, I don’t understand your question. Why not just use something like:
input type = “button” id=”x” name=”x” value=”test me” onclick=”show(’something’)”
And the js would be:
function show(who)
{
document.getElementById(’who’).style.display=”";
// presuming it had display=none;
}
The thing I was talking about in my post was about “clicking” something from inside javascript. Anyway, from what you’ve wrote, the correct thing would be to just write something like:
if (window.addEventListener) // random Mozilla only function; the fastest method to check if inside Mozilla compliant browser
{
HTMLElement.prototype.click = function() {
var evt = this.ownerDocument.createEvent(’MouseEvents’);
evt.initMouseEvent(’click’, true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
}
}
}
fileBrowser.click();
// That’s it
nice help ….
by the way the code snippet you have provided
having an extra brace , plz remove it
HTMLElement.prototype.click = function() {
var evt = this.ownerDocument.createEvent(’MouseEvents’);
evt.initMouseEvent(’click’, true, true, this.ownerDocument.defaultView, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
this.dispatchEvent(evt);
}
}///this brace has to be removed
I have the code below in a function that is called when I click on a button. No errors are thrown, but nothing happens. Please let me know what I am missing. Thanks.
var f = document.getElementById(’filImport’);
if (window.addEventListener)
{
alert(’Oh no…not Firefox.’);
HTMLElement.prototype.click = function()
{
var evt =
this.ownerDocument.createEvent
(’MouseEvents’);
evt.initMouseEvent(’click’,true,true,
this.ownerDocument.defaultView, 1,
0, 0, 0, 0, false, false, false,
false, 0, null);
this.dispatchEvent(evt);
}
}
f.click();
Same here guys, no errors but nothing happens. Anything I’m missing?
Thanks for the post! This is exactly what I was looking for. Haven’t had any issues with the code to-date.
not work…
but this.ownerDocument.createEvent(’MouseEvents’);
don’t require an autentication for security risk?
I use ff 3.5.1
Just tried this in Google Chrome (not the exact code, but I adapted it to my needs) and it worked great. If you’re not going to use it exactly as written like me, replace “this” with the object you’re trying to simulate the click on.
Genial dispatch and this mail helped me alot in my college assignement. Say thank you you on your information.
[...] Simulating mouse clicks in JavaScript [...]
Like Tarek mentioned, the extra “}” could be removed, but I must thank you, you’re a lifesaver!
I pass through ajax and ended up turning this into a funtion
function click(obj) {
and then used “obj” instead of “this”
Thanks
hey, I wanted to know that i have an input element of type=image.
now i want to simulate a click with initMouseEvent which could set the x and y values which are set when form associated is submitted
Worth noting that in order to fully simulate the action of the user clicking an element, you’ll want to fire a mousedown event, followed by a click event, followed by a mouseup event. Evidently some sites expect to receive all three events before they’ll assume the element has been clicked.