Search code examples
javascripthref

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.


Solution

  • <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>