I’m cloaking a referal link so I’m using an onClick function to open a new tab navigating to the linked website. However, I still want to display the url when the user hovers over the hyperlink text.
So if the referal link is: www.somelink.com/long_ref_code
then I would like to display only www.somelink.com
when the user hovers over the a element.
How do I achieve this?
Code:
function navigate(newtab){ var a = document.createElement('a'); a.href = "http://www.somesite.com/some_long_referal_code"; if (newTab) { a.setAttribute('target', '_blank'); } a.click(); }
And the element is:
<a onClick="navigate();">Some hyperlink text</a>
Advertisement
Answer
You can use preventDefault
to change the default action.
For example, here is an a element that opens it on the same tab (compatible with StackOverflow snippets). As you see, the URL when hovering says https://google.com, but the actual link it sends you to is https://mozilla.org
document.querySelector("a").addEventListener("click", event => { event.preventDefault(); window.location.assign("http://www.mozilla.org"); })
<a href="https://google.com">Google</a>