PDA

View Full Version : JS identifying hyperlink that triggered it by OnClick?


Seymour Clufley
09-06-2008, 11:08 PM
I'm writing a function that will be called by various hyperlinks. To cut down on code, I'd like the JS function to "know" which hyperlink called it, and be able to change its href.


<SCRIPT type="text/javascript">
function Redirect() {
// at this point, I need to identify the hyperlink and put it into "caller" variable
var oldhref = caller.href
alert("The id of the hyperlink that called this function is "+caller.id+" and its href is "+oldhref);
caller.href = "somewhere.html";
}
</SCRIPT>


<A id=testhyperlink href=graphic.jpg OnClick=Redirect()>Click to open graphic.</A>


I know I could do this by having an input parameter for the JS function but that would mean writing the hyperlink's ID twice (once in the ID field, once in the OnClick field) so I'd prefer to have the JS function do it automatically. Could this be achieved using the "this" keyword?

Seymour Clufley
09-07-2008, 01:24 AM
Ah, I've managed it.


<SCRIPT type="text/javascript">
function Redirect(caller) {
var oldhref = caller.href
alert("The id of the hyperlink that called this function is "+caller.id+" and its href is "+oldhref);
}
</SCRIPT>

<A id=testhyperlink href=graphic.jpg OnClick=Redirect(this)>Click to open graphic.</A>


The only thing to look out for is the JS will return the absolute path to the target, not the relative.