Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
116
rated 0 times [  122] [ 6]  / answers: 1 / hits: 45532  / 15 Years ago, wed, september 2, 2009, 12:00:00

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?


More From » jquery

 Answers
10

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;

  • the function parameter is called id yet you call event.preventDefault(); and

  • You're fading the post and then immediately showing it? That'll queue two animations but doesn't make a lot of sense. You probably want to chain together those two things and the load() 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.


[#98776] Friday, August 28, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
blair

Total Points: 384
Total Questions: 108
Total Answers: 86

Location: Northern Ireland
Member since Tue, May 5, 2020
4 Years ago
blair questions
Sat, Feb 12, 22, 00:00, 2 Years ago
Wed, Aug 25, 21, 00:00, 3 Years ago
Sat, Jul 10, 21, 00:00, 3 Years ago
Tue, Aug 25, 20, 00:00, 4 Years ago
;