Search code examples
javascriptjqueryhref

Place a variable as a HREF


Basically, is it possible to do something like....

<a href=link onClick="clicked();">Click me!</a>

<script>
function clicked() {
    if(myVar == 1) {
        link="http://stackoverflow.com"
    }
    else if (myVar == 2) {
        link="http://google.com"
    }
}
</script>

This example is probably impossible due to it firing at the same time... But is it at all possible to use variables there?

Basically, I need a link that'll bring you to two different places depending on a variable. I suppose I could have two links, and just hide/show each one respectively depending on the variable, but I was wondering if it's possible another way?

I'm working with HTML, CSS, JavaScript, and JQuery...

Thank you!


Solution

  • You could do...

    $('a').click(function(event) {
        if (condition) {
            event.preventDefault();
            window.location = 'http://different-url.com';
        }
    });
    

    If the condition is met, then it will take you to a different URL.

    Otherwise, the link will work as expected.

    If you didn't want to use jQuery, that'd be...

    var anchors = document.getElementsByTagName('a');
    for (var i = 0, anchorsLength; i < anchorsLength; i++) {
       anchors[i].onclick = function(event) {
          if (condition) {
              event.preventDefault();
              window.location = 'http://different-url.com';
          }
       }
    }