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

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?

This question is related to javascript html

The answer is


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);
}

for example try this :

<a href="http://www.google.com" id="myLink1">open link 1</a><br/> <a href="http://www.youtube.com" id="myLink2">open link 2</a>



    document.getElementById("myLink1").onclick = function() {
    window.open(
    "http://www.facebook.com"
        );
        return false;
      };

      document.getElementById("myLink2").onclick = function() {
    window.open(
    "http://www.yahoo.com"
        );
        return false;
      };


Replace

onclick="changeLink();"

by

onclick="changeLink(); return false;"

to cancel its default action


Is there any downside of leveraging mousedown listener to modify the href attribute with a new URL location and then let the browser figures out where it should redirect to?

It's working fine so far for me. Would like to know what the limitations are with this approach?

// Simple code snippet to demonstrate the said approach
const a = document.createElement('a');
a.textContent = 'test link';
a.href = '/haha';
a.target = '_blank';
a.rel = 'noopener';

a.onmousedown = () => {
  a.href = '/lol';
};

document.body.appendChild(a);
}

You can change this in the page load.

My intention is that when the page comes to the load function, switch the links (the current link in the required one)