Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browser-friendly way to simulate anchor click with jQuery?

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.

like image 619
ezkl Avatar asked Oct 28 '25 21:10

ezkl


1 Answers

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();
  }    
}
like image 72
Josh Stodola Avatar answered Oct 31 '25 12:10

Josh Stodola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!