How can i capture anchor clicks to navigate the page? (preferrably in jQuery)

It's really frustrating because i forgot to save in my favourites a video tutorial to do exactly this. I want to capture all attempts to navigate away from the page (via an anchor i.e. <a href="otherpage.html">), and only navigate them depending on some condition (which is only if they don't have unsaved changes on that page).

I remember the example i saw involved getting all the anchors on the page, and then overriding the "open" function? Would that make sense? Does an anchor have an "open" function, or just an onclick function??

The overridden function then performs the check, and returns true or false depending on whether or not the page should be allowed to navigate. Can anyone refresh me on how i would do this? .. or does any one have any other similar solutions?

Ideally solutions in jQuery, but anything in plain javascript will do.

Who is Participating?
Pawel WitkowskiConnect With a Mentor Senior Javascript DeveloperCommented:
Or just simply:
   if (!confirm("You wana go out?")) return false;

Open in new window

Michel PlungjanIT ExpertCommented:
<body onLoad="window.leaving=true" onBeforeUnload="return (leaving) ?'Are you sure':null">
<a href="leaving.html">Leaving</a>

<a href="staying.html" onClick="leaving=false">Leaving</a>

or the opposite

<body onLoad="window.leaving=false" onBeforeUnload="return (leaving) ?'Are you sure':null">
<a href="leaving.html" onClick="leaving=true">Leaving</a>

<a href="staying.html" >Leaving</a>
Pawel WitkowskiSenior Javascript DeveloperCommented:
try this
   var goThere=confirm("You wana go out?");
   if (!goThere) return false;

Open in new window

paddycobbettAuthor Commented:
This morning having gone through my whole browser history i finally found the link to the video tutorial i was looking for! And yes, it was exactly as you stated :)

thanks for your response
Michel PlungjanIT ExpertCommented:
If that works for you then why not just
   return confirm("You wana go out?");
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.