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

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

Leave a Reply




Advertisements