I have a piece of JavaScript that dynamically creates an A
tag inside of an existing div and then calls the jQuery function "click" on it. This works as intended in all browsers except Safari.
Safari returns the following error:
'undefined' is not a function (evaluating '$('.shell a')[0].click()')
Any ideas on what I'm doing wrong or why this doesn't work in Safari and how to get it to work (or one piece of code that works in all browsers) I've tried using .trigger("click")
as well and it gives the same error.
function writeAndClickLink(url) { $('.shell').html('<a href="' + url + '"></a>'); $('.shell a')[0].click(); }
and in the HTML:
<div class="shell"></div>
The reason I'm doing it this weird way is the function is called from a Flash site to open a twitter window where I am giving a reward for tweeting. This so far has been the only way I could get the "tweet" event to bind to the window. If I open the window any other way (window.open for example) it doesn't capture the bound event that lets me know they actually completed the tweet.
The flow is something like:
var a = $('.shell a')[0]; var evObj = document.createEvent('MouseEvents'); evObj.initMouseEvent('click', true, true, window); a.dispatchEvent(evObj);
See http://www.howtocreate.co.uk/tutorials/javascript/domevents (search for "Manually firing events").
Trevor Dixon's answer does fix Safari, but breaks in even the latest Firefox:
TypeError: Not enough arguments to MouseEvent.initMouseEvent
The best way to support Safari—without breaking Firefox—would be using initEvent
instead of initMouseEvent
like so:
var element = document.getElementById('your_id_here'); if(element.click) element.click(); else if(document.createEvent) { var eventObj = document.createEvent('MouseEvents'); eventObj.initEvent('click',true,true); element.dispatchEvent(eventObj); }
To update for 2016, MouseEvent
should be used instead of initMouseEvent
which is deprecated:
var eventObj = new MouseEvent("click", { bubbles: true, cancelable: true }); element.dispatchEvent(eventObj);
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