Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
22
rated 0 times [  26] [ 4]  / answers: 1 / hits: 36545  / 12 Years ago, fri, march 30, 2012, 12:00:00

I can't seem to find an example of what I'm trying to do here but I'm sure it's possible.



Consider the following:



<div id=main_nav>
<a href=/url/>LINK</a>
<a href=/url/>LINK</a>
<a href=/url/>LINK</a>
<a href=/url/>LINK</a>
</div>


How can I run a function when a link within #main_nav is clicked before then following the link?



The below doesn't work as the link is followed before the function is run.



$('#main_nav a').click(function() {
// Some Function
});


EDIT



I'm actually trying to clear a cookie with the JQuery cookie plugin when the links are clicked. I'm not sure if this is relevant or not.



The Clear cookie code is:



$.cookie('TMMenu', null);


TMMenu is the correct name and the plugin is loaded.



EDIT



Sorry everyone. The problem was actually with the JQuery Cookie plugin documentation.



$.cookie('TMMenu', null); 


as described in the readme doesn't seem to work. This does:



$.cookie('TMMenu', null, { path: '/', expires: -5 });

More From » jquery

 Answers
45

Update: Re your edit: I can't see any reason that wouldn't work other than #1 below.



I can think of two answers to this question:




  1. You're running your jQuery code before the #main_nav a element exists, and no event handler is hooked up. Put your script at the bottom of the HTML file, just before the closing </body> tag, or use the ready callback.


  2. You're doing something asynchronous in your handler, and not seeing it happen. That's because as soon as the event handler returns, the link gets followed — even if your handler initiates some asynchronous action.




Here's how to fix the second one (both, if you put this at the end or inside a ready handler):



$('#main_nav a').click(function(event) {
// Remember the link href
var href = this.href;

// Don't follow the link
event.preventDefault();

// Do the async thing
startSomeAsyncThing(function() {
// This is the completion callback for the asynchronous thing;
// go to the link
window.location = href;
});
});


(Live copy | source)


[#86508] Thursday, March 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
reed

Total Points: 725
Total Questions: 85
Total Answers: 89

Location: Singapore
Member since Sat, Jul 25, 2020
4 Years ago
;