Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 269
Dan Herbert Avatar asked Sep 27 '08 14:09

Dan Herbert


People also ask

How can I trigger a click event in JavaScript?

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.

Can JavaScript trigger 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.

How do you trigger a click event for a hyperlink?

Answer: Use the jQuery click() Method You can use the click() method to trigger a click on a link programmatically using jQuery.


1 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)    } } 
like image 97
Chris MacDonald Avatar answered Oct 18 '22 20:10

Chris MacDonald