I need to trigger the click event on a link and then, if none of the listeners prevented the default, change the location.
This is what I've got so far:
var $el = $('a#my_special_link');
var onClick = $el.attr('onclick');
// Hack to capture the event object
var ev_reference;
var ev_capture = function(ev) { ev_reference = ev; }
$el.bind('click', ev_capture);
// Don't leave out the onClick handler
if ( typeof onClick == 'function' )
$el.bind('click', onClick);
$el.trigger('click');
// Clean up
$el.unbind('click', ev_capture);
if ( typeof onClick == 'function' )
$el.unbind('click', onClick);
// Redirect if necessary
if ( ! ev_reference.isDefaultPrevented() )
window.location = $el.attr('href');
Any suggestions for improvement are welcome.
PS: Yes, it's just how a regular link would work, except you can do some other processing in between.
PPS: No, just doing $el.trigger('click'); will not change the location.