faqts : Computers : Programming : Languages : JavaScript

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

12 of 29 people (41%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

IS there a way in Javascript to capture the URL that was clicked on using onunolad or some event ?
This works, but I do not have access to the HREF line to add the onclick event. Is there a global e
With no access to the HREF, I can not get the onclick to pass the link to the script. From what I r
Thank you for your response.

Apr 7th, 2008 22:37
ha mo, Sharon Levy, Bemi Faison, jerome wolter,


You may capture the url of a link that a user clicks by using the 
onclick event associated with that link.  Here is a working example 
that I tested in IE6 and Netscape6.2:
<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<TITLE></TITLE>
<script>
var the_url_is = "";
</script>
</HEAD>
<BODY>
<P> </P>
</BODY>
</HTML>
HTH,
================================
You may want to assign a function to the onclick handler, in order to 
do the above AND prevent the URL from being followed.
/-----------snip
<SCRIPT LANGAUGE="JavaScript">
function doClick(lnk) {
    the_url_is = lnk.href; // capture url to a global variable
    alert(the_url_is); // report the captured url
    return false // prevent the anchor from changing the document
}
</SCRIPT>
...and in the body of your document...
<a href="otherpage.html" onclick="return doClick(this)">Capture URL</a>
-----------snip/
You might want to use this method, to perform some tests with the url 
or anchor object before letting the user access the page.
BTW: Both these examples work in all JavaScript enabled browsers.
===========================
Here's another possible solution based B. Faison's excellent revision 
of my script. But, the following version assigns an onclick event 
handler for the link in question in Javascript and not HTML, as follows:
<BODY>
<a id=somelink href="otherpage.html">Capture URL</a>
<script>
function doClick() {
    var the_url_is = somelink.href; // save url 
    alert(the_url_is); // report saved url
    return true;       // so user may proceed to otherpage.html
}
somelink.onclick=doClick; // assign onclick event handler
</script>
</BODY>
This works in IE6 and presumably in IE4+ as well. But, it fails in 
Netscape 6.2 and probably in previous Netscape versions, too.
http://www.businessian.com
http://www.computerstan.com
http://www.financestan.com
http://www.healthstan.com
http://www.internetstan.com
http://www.moneyenews.com
http://www.technologystan.com
http://www.zobab.com
http://www.healthinhealth.com