6

I have a link ('a' tag). I'm trying to click it using JavaScript. While .click(); does well in Firefox and IE but it fails in Chrome. (Chrome says the object does not have the click method).

Triggering the 'onclick' or redirecting to the 'href' won't do the job.

Any ideas on how to do this? Preferably I wouldn't get an entire library just for this.

0

6 Answers 6

2

In non-IE-browsers use dispatchEvent()

1
var event = document.createEvent("MouseEvents");
            event.initMouseEvent("click", true, true, window,
                0, 0, 0, 0, 0,
                false, false, false, false,
                0, null);
            element.dispatchEvent(event);

should work in chrome

0
1

I understand you do not want a library but this one's footprint is quite small, you can use event.simulate for this. it is a PrototypeJS lib, but i'm sure the porting would be very easy.

To use it in prototype you would call:

$('my_anchor').simulate('click');

It works cross-browser with no issues.

1
  • Thanks for the reminder to just use the library's method ... in the case of mootools, .fireEvent('click') is the right one.
    – joelhardi
    Feb 29, 2012 at 18:44
0

Try reading the referenced post there the author have the the same problem.
He solves it by running a script in the onLoad callback;

<body onLoad="DefaultButtonFix()">

Refernece: Click event fires in IE/Firefox, but Chrome is dropping the event assignment

0

I use this:

function dispatchEvent(el, e)
{
    // console.log("dispatching");

    if ("createEvent" in document)
    {
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(e, false, true);
        el.dispatchEvent(evt);
    }
    else
    {
        el.fireEvent("on" + e);
    }

}

dispatchEvent(document.getElementById("mylink"), "click");
-1

If you know jQuery simply create an anonymous function and listen for the onclick event. You will need to specify a class or id for you href,

e.g. HTML :

<a href='' id='clickMe'>Click here</a>

jQuery :

$(function() {  
  $("#clickMe").click(function() {
    ... the action you wish to perform ...
  }) 
})

Hope this helps. Dave

2
  • this only listens for a click event, the op wants to 'simulate' a click.
    – epoch
    Jan 10, 2012 at 10:25
  • Valid point, I should have read the op message more thoroughly! Jan 10, 2012 at 10:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.