How To Trigger Native Click Action (replay Event) Later?
Solution 1:
Up-to-date answer: yes, you can (assuming you no longer support IE8).
Use dispatchEvent() to fire a copy of the original event.
First you need an utility function to clone the event (as browsers only allow events to be dispatched once, for security reasons):
var cloneNativeMouseEvent = function (original) {
varcopy;
try {
copy = new MouseEvent(original.type, original);
} catch (stupidInternetExplorer) {
copy = document.createEvent('MouseEvent');
copy.initMouseEvent(original.type, original.bubbles, original.cancelable, original.view,
original.detail, original.screenX, original.screenY, original.clientX, original.clientY,
original.ctrlKey, original.altKey, original.shiftKey, original.metaKey, original.button,
original.relatedTarget)
}
returncopy;
};
In your click handler store a reference to the jQuery event for later replay:
$("#wrapper a").bind('click', function (event) {
event.preventDefault();
storedEvent = event;
...
}
And finally, in the callback where you want to trigger the click again, do it as follows:
var originalEventClone = cloneNativeMouseEvent(storedEvent.originalEvent);
storedEvent.target.dispatchEvent(originalEventClone);
Please note that, in general, events created or modified by JavaScript are marked as "not trusted" by user agents so they can't trigger default actions. Luckily click events are the only exception. (1)
Solution 2:
You cannot trigger a click event on an anchor and get it to follow the href cross browser.
Solution 3:
It turns out redsquare is basically correct -- it doesn't work without tearing your hair out.
IE is the problem. dispatchEvent() works fine in FireFox. In IE, you can choose fireEvent to fire any associated events (but not the click), or click() (for clicks but not events), but you can't do both properly.
I got it "almost working" by temporarily changing links' hrefs and targets so that they loaded a blank page in an iframe. I then listened for iframe "load" events to determine if the link's default action had taken place. In IE I could then fire "click" if needed, or "fireEvent" otherwise, after changing the href and target back.
However, it was too much of a hack -- what if one of the links has a bound event that relied on the href attribute being there? (thickbox seemed to carry on working, but I expect it was a race condition).
In the end I didn't need to do it at all anyway ( JavaScript/jQuery: How to make sure cross-domain click tracking event succeeds before the user leaves the page? ), so I am relieved. It turns out that I had to use POST in this case.
Post a Comment for "How To Trigger Native Click Action (replay Event) Later?"