Reputation: 1462
I want to set dynamic links to a href link. What i exactly need to do is to call a js method which returns the url according to domain inside the a href.
<a href="javascript:getAuthUrl()"><u>Login>></u></a>
function getAuthUrl() {
...
if (domain.includes("localhost")) {
return buildOAuthUrl(hostConfig.dev);
}
else if (domain.includes("...")) {
return buildOAuthUrl(hostConfig.test);
}
else if (domain.includes("....")) {
return buildOAuthUrl(hostConfig.uat);
}
else if (domain.includes("....")) {
return buildOAuthUrl(hostConfig.prod);
}
else if (domain.includes("....")) {
return buildOAuthUrl(hostConfig.test);
}
else {
return buildOAuthUrl(hostConfig.dev);
}
}
}
I tried some examples in stackoverflow but that didn't solve my error/problem.
Upvotes: 3
Views: 3282
Reputation: 509
Although 'CertainPerformance' has answered it well. Adding another version incase you want to have it in line with question.
You can use DOM manipulation with anchor tags onClick event directly.
Example:
function getAuthUrl() {
url="";
if (domain.includes("localhost")) {
url=buildOAuthUrl("dev");
}
else if (domain.includes("...")) {
url=buildOAuthUrl("test");
}
else if (domain.includes("....")) {
url=buildOAuthUrl("uat");
}
var b = document.querySelector("#url");
b.setAttribute("href", url);
}
<a id="url" href="" onclick="getAuthUrl()"><u>Login>></u></a>
Upvotes: 4
Reputation: 371168
Try adding an event listener instead of using inline eval:
document.querySelector('a').addEventListener('click', (e) => {
if (Math.random() < 0.5) e.target.href = 'https://stackoverflow.com/questions/49605314/set-dynamic-url-to-a-href-in-javascript/49605338';
else e.target.href = 'https://stackoverflow.com';
});
<a>go somewhere</a>
(make sure not to use e.preventDefault()
if you want to preserve the ordinary link-click handling)
Upvotes: 1