I have a simple Javascript function which builds a Url that I want to provide a link to.
However, I can't seem to get the anchor tag working with it. How do I assign the href of the anchor tag the results of the Javascript function?
Neither one of these work correctly:
<a href="getUrl();">Click here</a>
<a href="javascript:getUrl();">Click here</a>
This is what I want to accomplish.
In JavaScript, you can call a function or snippet of JavaScript code through the HREF tag of a link. This can be useful because it means that the given JavaScript code is going to automatically run for someone clicking on the link. HREF refers to the “HREF” attribute within an A LINK tag (hyperlink in HTML).
A href JavaScript function call | Example code Simple use javascript:void(0) as the value of href and onclick method function name to call JavaScript function. Or another way is to use javascript:method_name as the value of href.
The anwer is: not possible.
<script type="text/javascript">
function getUrl()
{
return "http://www.google.com";
}
</script>
<a href="javascript:document.location.href=getUrl();">Click here</a>
-- update --
If I wanted to incorporate user278064s' comments, i would change the above into:
<script type="text/javascript">
function getUrl()
{
return "http://www.google.com";
}
</script>
<a href="#" onClick="document.location.href=getUrl();">Click here</a>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With