3

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&gt;&gt;</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.

2
  • what error that you got? can you elaborate more Commented Apr 2, 2018 at 4:33
  • Could you please add complete code ? Commented Apr 2, 2018 at 4:35

2 Answers 2

4

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&gt;&gt;</u></a>
Sign up to request clarification or add additional context in comments.

1 Comment

Using ".onclick", ".onchange", or "on" anything is bad practice and results in poorly factored, hard-to-manage code; as well as limiting you to one event listener per event. Consider attaching your events with addEventListener, instead, eg: developer.mozilla.org/en/DOM/element.addEventListener
1

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)

1 Comment

It's just an example - of course on the real page he should somehow select the particular a he wants to change and add the listener to that (but I don't know how his HTML is set up)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.