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:
enter code here
To extract my notes to others posts: (another way to say same basic stuff)
<a href="somewhere" id="mylink">MyLink</a>
<script>jQuery('#mylink').click(function(){
// do whatever I want here, then redirect
window.location.href = "http://stackoverflow.com";
});
function doClick(){
jQuery('#mylink').trigger('click');
};
// trigger the redirect now
doClick();
</script>
EDIT1:@ comments:
If the "other" you describe returns false, you at that point, terminate the callback with the false - so you are correct but has nothing to do with this handler. Which ever one hits first executes, and the other never does return, and this one redirects prior to the other one hitting the log if it executes first.
In order to put your log in, you put that where I have my
"// do whatever I want here, then redirect"
comment To remove the other event, then bind with this one only:
<a href="somewhere" id="mylink">MyLink</a>
<script>jQuery('#mylink').unbind('click').bind('click', function(){
// do whatever I want here, then redirect
window.location.href = "http://stackoverflow.com";
});
function doClick(){
jQuery('#mylink').trigger('click');
};
// trigger the redirect now
doClick();
"if none of the listeners prevented the default, change the location."
Sounds exactly how a normal link behaves...?
Anyway, if you are trying to look for "return false", it will not be found using isDefaultPrevented()
, which only will return true if preventDefault()
is called from the same event object. In this example, I'm sending the event object to whatever()
and if that function sets preventDefault()
, the window will relocate anyway (is that what you need...?)
$('a#my_special_link').bind('click', function(e) {
whatever(e);
if (e.isDefaultPrevented()) {
window.location = $(e.target).attr('href');
}
});
http://docs.jquery.com/Events/trigger#eventdata
$('a#my_special_link').trigger("click");
If I understand your question correctly, you have an a
element that you don't control, which has an onclick
attribute that returns false
. Returning false
from an onclick handler prevents a click on the link from taking you to the linked page. And you don't want that.
You could store the onclick
handler function and then remove it from the link element:
var $a = $('#my_special_link');
var onclickHandler = $a.attr('onclick');
$a.removeAttr('onclick');
Then cal the stored handler function in your custom click handler:
$a.click(function() {
// ...
onclickHandler();
// ...
});