skip to Main Content

I want to pass a function to href in my a tag link but no matter what I try it doesn’t work. it either leads to a 404 page or is not even clickable. What am I doing wrong?

this is not clickable

<body>
<a id="specialLink" href="#" onClick="redirectToApp()">click me</a>
<script>
document.getElementById('specialLink').href = redirectToApp();
function redirectToApp () {
    return "http://www.google.com";
} 
</script>
</body>

this is not clickable

<body>
<a href="#" onClick="document.location.href=redirectToApp()">click me</a>
<script>
function redirectToApp () {
    return "http://www.google.com";
} 
</script>
</body>

this leads to a 404 page

<body>
<a href="javascript:document.location.href=redirectToApp();">click me</a>
<script>
function redirectToApp () {
    return "http://www.google.com";
} 
</script>
</body>

I should maybe also say that I am sending this HTML via email, from which the link should be opened and unless I just pass the URL as a string to href nothing is working

2

Answers


  1. you can try this:

    const anchor = document.getElementById('specialLink')
    anchor.addEventListener((e) => {
        e.preventDefault()
        window.open("https://google.com");
    
    })
    

    and remove onClick on the anchor tag

    Login or Signup to reply.
  2. With the first approach instead of using

    <a id="specialLink" href="#" onClick="redirectToApp()">click me</a>
    

    You can try out this:

    <a id="specialLink" href="redirectToApp()" target="_blank">click me</a>
    

    I have added a JS fiddle for you:
    https://jsfiddle.net/26ac0x7p/2/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search