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
you can try this:
and remove
onClick
on the anchor tagWith the first approach instead of using
You can try out this:
I have added a JS fiddle for you:
https://jsfiddle.net/26ac0x7p/2/