Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 515
  • Last Modified:

Use javascript to get the href value of a clicked link

Is there a way to use javascript to get the href value of a link that was clicked when onUnLoad is fired? I want to create a function that runs when a page unloads and somehow get the href value of the link that user clicked to leave the page.

So like this:
<script>
function Redirect() {
var linkclicked="this will be the value of whatever link was clicked";
}
</script>

<body onUnLoad="Redirect()">

<div class="leave"><a href="http://www.google.com">Leave to Google</a></div>

and when the user clicks "Leave to Google" the value "http://www.google.com" will be put into the variable "linkclicked"  
but the tricky part is that I can't add anything to the link itself. The solution must be contained within the javascript function.

Thanks.
0
elliottbenzle
Asked:
elliottbenzle
2 Solutions
 
SRigneyCommented:
with jQuery I would do this.

$("a").click(function() {
   // do what you want with the value.
  $(this).attr("href");
});


The same thing can be done with straight javascript, but I'm more of a jQuery expert.  The click event should fire before the page unloads.
0
 
ZvonkoSystems architectCommented:
This is a very basic example what can be done:


<script>
var linkclicked
function Redirect() {
  alert("linkclicked: "+linkclicked);
}

function addClicks(){
  var lnk = document.links;
  for(var i=0;i<lnk.length;i++){
    lnk[i].onclick=function(){linkclicked=this.href;}
  }
}
</script>

<body onLoad="addClicks()" onUnLoad="Redirect()">

<div class="leave"><a href="http://www.google.com">Leave to Google</a></div>


0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

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.

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