Search code examples
javascripthref

Javascript: embedding a result of a function into a HREF


I have a javascript function that reformats a link. When a HREF link is clicked, I need to execute this method to finish creating the HREF.

Example JS method:

function fixURL (dest, val){
   return dest + val;
}

I have an regular HREF and would like to combine the result of the above method to create:

<a href="http://www.site.com/" + fixURL('poo','no')>Click me!</a>

Is this possible and is it ideal to do so?


Solution

  • You can use an onclick handler. Note, you're generally better off not using inline event handlers like onclick="something...", so this is just for demonstration purposes.

    Also, this will try to open a new window/tab with the search result.

    <a target="_blank"
       href="https://www.google.com/search?q=chris+rock"
       rel="chris+rock|dave+chappelle"
       onclick="fixURL(this)">Test</a>
    
    function fixURL(el){
        var vals = el.rel.split('|');
        el.href = el.href.replace(vals[0],vals[1]);
    }
    

    http://jsfiddle.net/sxtuz/1/

    The same effect, only using DOM event handlers. Note the id="fixme" attribute.

    <a id="fixme"
       target="_blank"
       href="https://www.google.com/search?q=chris+rock"
       rel="chris+rock|dave+chappelle">Test</a>
    
    function fixURL(el){
        var vals = el.rel.split('|');
        el.href = el.href.replace(vals[0],vals[1]);
    }
    window.onload = function(){
        document.getElementById('fixme').onclick = function(){
            fixURL(this);
        };
    }
    

    http://jsfiddle.net/sxtuz/