Link to home
Start Free TrialLog in
Avatar of paddycobbett
paddycobbett

asked on

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.

Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

<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>
 
try this
$("a").each({
this.onclick=function()
{
   var goThere=confirm("You wana go out?");
   if (!goThere) return false;
}
})

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Pawel Witkowski
Pawel Witkowski
Flag of Poland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of paddycobbett
paddycobbett

ASKER

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
If that works for you then why not just
   return confirm("You wana go out?");