4

I'm trying to simulate a click on an anchor tag using jQuery. I've been digging around StackOverflow and Google for a while and haven't found anything that works on all of the browsers I'm testing. So far, I've found this:

$(document).ready(function() {
 $.fn.fireEvent = function(eventType) {
     return this.each(function() {
         if (document.createEvent) {
             var event = document.createEvent("HTMLEvents");
             event.initEvent(eventType, true, true);
             return !this.dispatchEvent(event);
         } else {
             var event = document.createEventObject();
             return this.fireEvent("on" + eventType, event)
         }
     });
 };

  $('a').fireEvent('click');
});

This will fire a click event in Safari, but not FireFox or the version of IE I tested. So, oh mighty minds of SO, what am I doing wrong? Any guidance would be greatly appreciated.

ezkl
  • 3,829
  • 23
  • 39
  • What is it you're trying to achieve? Is it to get a browser to follow the link or trigger another event? – jammus Nov 12 '09 at 14:48
  • I'm trying to get the browser to follow the link. It seems so simplistic, but I've been coming up empty for a few hours, so I figured I'd post it here. – ezkl Nov 12 '09 at 14:54
  • how about $('a').click(function(){location.href = this.href}).click(); ? It's a little silly but it works. – jammus Nov 12 '09 at 15:03
  • Interesting timing of this question. See also http://stackoverflow.com/questions/1722863/how-to-click-a-link-from-javascript – Roatin Marth Nov 12 '09 at 15:48
  • 1
    See @Josh' answer for how to get it to work in IE. Re Firefox (re-iterating what I said at http://stackoverflow.com/questions/1722863/how-to-click-a-link-from-javascript/1722881#1722881), you cannot achieve page navigation with `dispatchEvent` (all FF versions to date). Although the the usual "fire event handlers" + "bubble and repeat" does happen with `dispatchEvent`, Firefox simply doesn't navigate to the url in the `href` attribute. See http://stackoverflow.com/questions/809057/how-do-i-programmatically-click-on-an-element-in-firefox/809611#809611 IMO it's a bug. – Crescent Fresh Nov 12 '09 at 16:04

4 Answers4

4

This should work...

$(function() {

  fireClick($("a")[0]);

});

function fireClick(elem) {
  if(typeof elem == "string") elem = document.getElementById(objID);
  if(!elem) return;

  if(document.dispatchEvent) {   // W3C
    var oEvent = document.createEvent( "MouseEvents" );
    oEvent.initMouseEvent("click", true, true, window, 1, 1, 1, 1, 1, false, false, false, false, 0, elem);
    elem.dispatchEvent(oEvent);
  }
  else if(document.fireEvent) {   // IE
    elem.click();
  }    
}
Josh Stodola
  • 81,538
  • 47
  • 180
  • 227
  • Just tried this. No love on either Safari 4 or FireFox 3.0.11 on a Mac. – ezkl Nov 12 '09 at 14:45
  • All of the alerts get fired, but the DOM click itself doesn't on either of the browsers I'm testing. – ezkl Nov 12 '09 at 14:51
  • OK I have updated my answer to use a function I found online that implements the W3C standard for dispatching events. Please try this on Firefox, because I can not. – Josh Stodola Nov 12 '09 at 15:03
  • 1
    Hmm. Works in Safari, but not FireFox. Nothing in FireBug's error console to indicate why. – ezkl Nov 12 '09 at 15:14
  • I think FireFox simply blocks this kind of behavior. It probably deems a programmatic click on a link as some sort of security risk. – Josh Stodola Nov 12 '09 at 15:34
  • Heh, hello again Josh. Just to re-iterate what I said here http://stackoverflow.com/questions/1722863/how-to-click-a-link-from-javascript/1722881#1722881 for posterity, this code will have no effect in Firefox (all versions). Although the `document.dispatchEvent` code path will be hit (and the usual "fire event handlers" + "bubble and repeat" does happen as you've specified it should), Firefox simply doesn't navigate to the url in the `href` attribute. See http://stackoverflow.com/questions/809057/how-do-i-programmatically-click-on-an-element-in-firefox/809611#809611 IMO it's a bug. – Crescent Fresh Nov 12 '09 at 16:00
  • It will work in other browsers and IE however (which addresses part of the OP's problem), so +1 from me. – Crescent Fresh Nov 12 '09 at 16:09
3

Use $('a').click();

Tim S. Van Haren
  • 8,861
  • 2
  • 30
  • 34
  • This will fire the jQuery click event handler, no? I believe you have to get to the underlying DOM element to fire the event properly. See my answer. – Josh Stodola Nov 12 '09 at 14:41
  • This is the first thing that I tried. It doesn't work (for me) on either Safari 4 or FireFox 3.0.11. – ezkl Nov 12 '09 at 14:42
  • 1
    -1 Confirmed: this only fires the event handler assigned to the anchor via jQuery. It does not simulate a user clicking the link. It does not redirect to the HREF. – Josh Stodola Nov 12 '09 at 14:51
  • Something must have changed from 2012 to 2013, because this works perfectly for me, so +1. – Geeky Guy Oct 08 '13 at 13:52
1

I tested this in Chrome and Firefox but don't have an IE handy. This should work transparently in most scenarios.

$('a').live('click.simclick', function(event){
    var $a = $(event.target)
    setTimeout(function(){
        if (event.isPropagationStopped())
            return

        $('<form/>')
            .attr({
                method: 'get',
                target: $a.attr('target'),
                action: $a.attr('href')
            })
            .appendTo(document.body)
            .submit()

             // clean up in case location didn't change
            .remove()
    }, 0)
})

// test it
$('a').eq(0).click()
elijahr
  • 111
  • 7
0

I use this approach. Seems to work okay.

$(function() {
    fireClick($("a"));
});

function fireClick (elem) {
    window.location = $(elem).attr('href');
}
JeffRegan
  • 1,322
  • 9
  • 25