Simulate a click on the 'a' tag in Chrome

I have a link (tag 'a'). I am trying to click it using javascript. Bye .click (); works well in FF en IE, it does not work in Chrome. (chrome says the object has no click method).

running onclick or redirecting to href will not do the job.

any ideas on how to do this? Preferably, I would not get the whole library just for this.

+6
source share
6 answers
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

+1
source

In non-IE browsers, use dispatchEvent ()

+2
source

I understand that you do not want a library, but this size is very small, you can use event.simulate . this is PrototypeJS lib, but I'm sure porting will be very easy.

To use it in a prototype, you must call:

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

It works cross browser without any problems.

+1
source

Try to read the link post there, the author has the same problem.
He solves it by running the script in the onLoad callback;

 <body onLoad="DefaultButtonFix()"> 

Refernece: Click event in IE / Firefox, but Chrome discards event destination

0
source

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"); 
0
source

If you know that jQuery just creates an anonymous function and listens for the onclick event. You will need to specify a class or id for href,

eg. HTML:

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

jQuery:

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

Hope this helps. Dave

-1
source

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


All Articles