There might A mousebe 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:

  1. Extend/create the click function for the HTMLElement
  2. 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”.
  3. 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.
  4. 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);
}
Save and share: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • bodytext
  • Sphinn
  • del.icio.us
  • Mixx
  • Google
  • StumbleUpon
  • Technorati
  • YahooMyWeb

Comments

21 Responses to “Simulating mouse clicks in JavaScript”

  1. Justin on April 22nd, 2008 8:55 pm

    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.

  2. Bogdan on April 23rd, 2008 2:30 pm

    Thanks for the comment. Will definitely dig into it as the time allows it.

  3. Venkatesh on July 1st, 2008 8:49 am

    I tried the same code snippet with select element its not working can you give some inputs regarding that.

  4. Bogdan on July 5th, 2008 11:22 am

    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.

  5. Calvin on July 9th, 2008 5:42 pm

    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.

  6. Calvin on July 9th, 2008 6:15 pm

    I am using firefox 3.o

  7. Bogdan on July 10th, 2008 4:39 pm

    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 :)

  8. Piyal on August 24th, 2008 8:07 pm

    nice help ….

  9. Tarek Ahmed on March 2nd, 2009 9:29 pm

    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

  10. Matt on April 21st, 2009 7:44 pm

    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();

  11. Noam on June 3rd, 2009 2:55 pm

    Same here guys, no errors but nothing happens. Anything I’m missing?

  12. Kevin on July 16th, 2009 7:30 pm

    Thanks for the post! This is exactly what I was looking for. Haven’t had any issues with the code to-date.

  13. ste on July 28th, 2009 10:19 am

    not work…

    but this.ownerDocument.createEvent(’MouseEvents’);

    don’t require an autentication for security risk?

    I use ff 3.5.1

  14. Martin on April 4th, 2010 3:06 pm

    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.

  15. Wordpress Themes on September 24th, 2010 1:41 pm

    Genial dispatch and this mail helped me alot in my college assignement. Say thank you you on your information.

  16. Quick tip: firing ‘change’ event on inputs remotely | Kasia.Drzyzga on November 22nd, 2010 3:30 pm

    [...] Simulating mouse clicks in JavaScript [...]

  17. Juapornogboudi- Teap -Nicoutcha 7 on May 28th, 2011 6:12 am

    Like Tarek mentioned, the extra “}” could be removed, but I must thank you, you’re a lifesaver!

  18. mayan 2012 calendar on August 14th, 2011 2:11 am

    I pass through ajax and ended up turning this into a funtion

    function click(obj) {

    and then used “obj” instead of “this”

  19. 颂赞 on October 7th, 2011 4:54 pm

    Thanks

  20. SohanChotia on November 22nd, 2011 1:57 am

    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

  21. Pilch on January 13th, 2012 8:43 pm

    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.

Leave a Reply




Advertisements