views:

481

answers:

3

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.

+2  A: 

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

Tim S. Van Haren
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
This is the first thing that I tried. It doesn't work (for me) on either Safari 4 or FireFox 3.0.11.
wavvves
-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
+1  A: 

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
Just tried this. No love on either Safari 4 or FireFox 3.0.11 on a Mac.
wavvves
All of the alerts get fired, but the DOM click itself doesn't on either of the browsers I'm testing.
wavvves
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
Hmm. Works in Safari, but not FireFox. Nothing in FireBug's error console to indicate why.
wavvves
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
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
It will work in other browsers and IE however (which addresses part of the OP's problem), so +1 from me.
Crescent Fresh
A: 

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