Browser-friendly way to simulate an anchor click using jQuery?

I am trying to simulate a click on an anchor tag using jQuery. I delved into StackOverflow and Google for a while and did not find anything that works in all the browsers I am testing. So far I have 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 the click event in Safari, but not the FireFox or IE version that I tested. So, about the powerful minds of SO, what am I doing wrong? Any guidance would be greatly appreciated.

+3
source share
4 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();
  }    
}
+3
source

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

+3
source

I tested this in Chrome and Firefox, but I don't have IE. 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()
+1
source

I use this approach. Everything seems to be in order.

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

function fireClick (elem) {
    window.location = $(elem).attr('href');
}
0
source

Source: https://habr.com/ru/post/1722695/


All Articles