• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 325
  • Last Modified:

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.

0
paddycobbett
Asked:
paddycobbett
  • 2
  • 2
1 Solution
 
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>
 
0
 
Pawel WitkowskiSenior Javascript DeveloperCommented:
try this
$("a").each({
this.onclick=function()
{
   var goThere=confirm("You wana go out?");
   if (!goThere) return false;
}
})

Open in new window

0
 
Pawel WitkowskiSenior Javascript DeveloperCommented:
Or just simply:
$("a").click(function()
{
   if (!confirm("You wana go out?")) return false;
}
);

Open in new window

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

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now