I'm trying to prevent A HREF from actually opening the link, but to execute a script. I got the script part working, but it seems Firefox would just ignore this:
$("#permalink a").click(function(id){
$("#newPost").fadeToggle;
event.preventDefault();
var id = this.getAttribute('href');
$("#newPostContent").load(id);
$("#newPost").show("fast");
});
Can anyone suggest a cross-browser script for preventing defaults?
preventDefault() The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
preventDefault() will not allow the user to leave the page and open the URL. The event. stopPropagation() method stops the propagation of an event from occurring in the bubbling or capturing phase.
preventDefault() Prevents the browsers default behaviour (such as opening a link), but does not stop the event from bubbling up the DOM.
There is no opposite method of event. preventDefault() to understand why you first have to look into what event. preventDefault() does when you call it. Underneath the hood, the functionality for preventDefault is essentially calling a return false which halts any further execution.
The standard solution to this is to return false
from the click()
handler. return false
is the equivalent of calling preventDefault()
and stopPropagation()
on the event. preventDefault()
is sufficient for this task too so either it or return false
will work.
Your problem seems to be syntax errors and misnamed parameters. I see:
fadeToggle
has no parentheses;id
yet you call event.preventDefault()
; andload()
in a rational manner.So this should work:
$("#permalink a").click(function(event) {
$("#newPost").fadeToggle();
var id = this.getAttribute('href');
$("#newPostContent").load(id);
$("#newPost").show("fast");
return false;
});
You can freely replace return false
with event.preventDefault()
in this instance but the propagating click()
event might or might cause other issues depending on what other event handlers you have.
This always works: Firefox needs the "event handler", Chrome doesn't. So this works on all browsers:
$('#id_obj').click(function(event) {
event.preventDefault(event);
}
$("#permalink a").click(function(id){
should be
$("#permalink a").click(function(event){
Then
var id=event.target;
will give you the object you're working on, and event.preventDefault() will stop the default action.
Typically I return false; myself, but this both prevents the default action and stops propagation of the event, which might have effects you didn't expect with other event handlers.
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