Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change href attribute using JavaScript after opening the link in a new window?

Tags:

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?

like image 785
Mike Elucidate Avatar asked Mar 13 '13 12:03

Mike Elucidate


People also ask

How do I change a link in href?

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.

What is location HREF in JavaScript?

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.


2 Answers

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; } 
like image 117
Pete Avatar answered Sep 22 '22 05:09

Pete


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); } 
like image 36
jcubic Avatar answered Sep 21 '22 05:09

jcubic