Is it possible to trigger a link's (or any element's) click event through JavaScript?

Viewed 68956

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.

6 Answers

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();

It's not generally possible, afaik, mozilla has the click() method but for input elements only, not links.

Why don't you just create a function that the button will call on the onClick handler and, whenever you want to 'click' the button call the function instead?

Mozilla has a stricter policy for allowed JS actions/events - I had similar problems with the click() event too. It's disabled on some elements to prevent XSS.

What is wrong with redirecting the browser? This sould work everywhere.

Related