Jose M.
Jose M.

Reputation: 2330

How to set a hyperlink as a variable

I have the following code:

<div><input id="ShopButton" type="button" onclick="window.location.href='http://www.hyperlinkcode.com/button-links.php'"</div>

Works fine, except now my hyperlink is going to be dynamic. So my question is, how can I set up a variable and then pass it to the onclick event? The hyperlink will be stored on a variable called StrUCode.

I know I have to declare the variable, but how do I work it into my button?

I am stumbling through html/javascript, just getting my feet wet.

Thanks

Upvotes: 1

Views: 82

Answers (1)

Joe
Joe

Reputation: 8262

If you do not want to use inline js like me:

var StrUCode = "http://example.org";
document.querySelector("#ShopButton").addEventListener("click",function(){
    window.location.href=StrUCode;
},false);

Use EventTarget.addEventListener(); to listen to events on an element like: click, mouseover, etc.


//You can use functions too:

var StrUCode = "http://example.org";
document.querySelector("#ShopButton").addEventListener("click",function(){
    redirectMe(StrUCode);
},false);

function redirectMe(url){
    window.location.href=url;
};

Upvotes: 1

Related Questions