I have a link on my page
<a href="http://google.com" id="mylink" onclick="changeLink();" target="_blank">google</a>
And the goal is to follow this link (opening in a new tab) and change its attributes (on previous tab). I mean we open google.com in a new tab and if we look back on the link, it's refreshed.
I've tried this js code
function changeLink(){ document.getElementById("mylink").href = "http://facebook.com"; document.getElementById("mylink").innerHTML = "facebook"; }
But it also changes the target of new opening tab. Instead of opening google it opens facebook in my example.
Is it possible to fix it?
Answer: Use the jQuery . attr() Method attr() method to dynamically set or change the value of href attribute of a link or anchor tag. This method can also be used to get the value of any attribute.
href. The href property of the Location interface is a stringifier that returns a string containing the whole URL, and allows the href to be updated.
Your onclick
fires before the href so it will change before the page is opened, you need to make the function handle the window opening like so:
function changeLink() { var link = document.getElementById("mylink"); window.open( link.href, '_blank' ); link.innerHTML = "facebook"; link.setAttribute('href', "http://facebook.com"); return false; }
You can delay your code using setTimeout
to execute after click
function changeLink(){ setTimeout(function() { var link = document.getElementById("mylink"); link.setAttribute('href', "http://facebook.com"); document.getElementById("mylink").innerHTML = "facebook"; }, 100); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With