Mike Elucidate
Mike Elucidate

Reputation: 263

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?

Upvotes: 26

Views: 187774

Answers (7)

Aris
Aris

Reputation: 9

for example try this:

<a href="http://www.google.com" id="myLink1">open link 1</a>
<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;
};

Upvotes: 0

user20417202
user20417202

Reputation: 1

Well in my own Case it was a react code i used a map method on my nav links and the href attibute simply takes you to to the place in the page.

<ul className="app__navbar-links">{[
              "About",
              "Impact report",
              "Our programs",
              "Resources",
              "Blog",
              "Free downloads",
              "Join community",
            ].map((item, index) => (
              <li className="app__flex" key={index}>
                <div />

                <a href={`#${item}`} id="nav-link" onClick={handleBlogClick}>
                  {" "}
                  {item}
                </a>
              </li>
            ))}
          </ul>

i needed a new tab only on the blog nav. The set Attribute opens a new tab but it doesnt default to the new tabs origin and it refreshes the whole page. But this solution worked for me.

const handleBlogClick = (event) => {
    const navLink = document.querySelectorAll("#nav-link");
    if (event.target === navLink[4]) {
      const blogNav = navLink[4];
      console.log(blogNav);
      console.log(event.target.innerHTML);
      window.open(
        "https://www.linkedin.com/company/ideas-worth-billions/",
        "_blank",
        "noopener,noreferrer"
      );

      blogNav.innerHTML = "Blog";
      return false;
    }
  };

Upvotes: 0

motss
motss

Reputation: 668

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

Upvotes: -1

Pete
Pete

Reputation: 58452

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

Upvotes: 60

Hodaya Shalom
Hodaya Shalom

Reputation: 4417

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)

Upvotes: 0

artahian
artahian

Reputation: 2103

Replace

onclick="changeLink();"

by

onclick="changeLink(); return false;"

to cancel its default action

Upvotes: 3

jcubic
jcubic

Reputation: 66590

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

Upvotes: 5

Related Questions