Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html link, href assignment from a Javascript function

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.

like image 483
Mike Avatar asked Aug 04 '11 17:08

Mike


People also ask

Can we call a JavaScript function on a href?

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).

How do you call a href inside a function?

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.

Can we pass function to href?

The anwer is: not possible.


1 Answers

<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>
like image 160
micha Avatar answered Sep 27 '22 16:09

micha