JavaScript – why simulating a click using the click() method doesn’t work in Chrome
Chrome doesn't allow simulating a click using the click() method.
While working on some WordPress plugin to enhance the comment system with a couple of Ajax features, i ran into a problem. My code was using the click() method on a link object to simulate a click on this link and while this did work fine in Opera, Firefox and Internet Explorer, it did not so in Google Chrome. Now, I know using click() is a bad thing and there is almost always a better way but in this specific case, there wasn't so I had to find a solution.
The reason why Chrome doesn't allow this is most likely related to its security model and I think it does it on purpose which is all fine, because such functionality is rarely, if ever, needed.
So here is a solution that seems to work:
var cancel_button = document.getElementById('cancel-comment-reply-link');
if(isValidObject(cancel_button)) {
if(cancel_button.style.display != 'none') {
try {
cancel_button.click();
}
catch(e) {
var event = document.createEvent("MouseEvents");
event.initMouseEvent("click", true, true, window,0, 0, 0, 0, 0, false, false, false, false, 0, null);
var _r = !cancel_button.dispatchEvent(event);
}
}
}
The code assumes that cancel_button is a simple link and isValidObject() is just a helper function in my code to check whether an object does exist to avoid JavaScript errors. The try/catch construct is another necessity, because some testing revealed that the event method does not work in Internet Explorer, but the simpler click() method works just fine. Oh well, browsers...
I know that cancel-comment-reply-link and its response to click events is handled by some WordPress JavaScript code in comment-reply.js, so a different solution would be to use just this code, but I opted against this method, because it would probably break when this code would change in a future WordPress update.
