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.
The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.
HTML events are handled by JavaScript. When an event occurs, it requires some action to be taken. This action can be accomplished through JavaScript event handlers. In addition to JavaScript, jQuery which is equivalent to JavaScript in terms of functionality can also be used to trigger events in a HTML document.
Answer: Use the jQuery click() Method You can use the click() method to trigger a click on a link programmatically using jQuery.
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) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With