Is it possible to trigger a link's (or any element's) click event through JavaScript?
I'm writing some JavaScript code that needs to fire the click
event for a link. In Internet Explorer I can do this
var button = document.getElementById('myButton');
button.click();
But this doesn't work in Firefox, and I assume any other browser. In Firefox, I've done this
var button = document.getElementById('myButton');
window.location = button.href;
I feel like this is not the best way to do this. Is there a better way to trigger a click
event? Preferably something that works regardless of the type of element or the browser.
http://jehiah.cz/archive/firing-javascript-events-properly
function fireEvent(element,event) {
if (document.createEvent) {
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
} else {
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
}
}
I wouldn't recommend it, but you can call the onclick attribute of an HTML element as a method.
<a id="my-link" href="#" onclick="alert('Hello world');">My link</a>
document.getElementById('my-link').onclick();