Question

So, I have some links in my page (< a > type), marked with different ID-s. They have those attributes:

  1. id - the unique id of each link
  2. href - the URL, that will open in new tab /!important -> The link needs to be opened in new tab!/
  3. target="_blank" - for the link to open in new tab

So, the links look like:

<a id="a1" href="thelink" target="_Blank">Link1</a>
<a id="a2" href="thelink" target="_Blank">Link2</a>
<a id="a3" href="thelink" target="_Blank">Link3</a>
etc..

I want when one link is clicked, the URL to open in a new tab, and the link in the original page to be disabled, but not that way:

<a id="a3" href="#" target="_Blank">Link1</a

I tried using onclick to remove the "href" attribute and onclick to empty the "href" attribute but the link doesnt open, as the onclick fires first and removes the "href" element, before the link opens in new tab and the effect is not the one that i want. Got some Ideas guys?

Was it helpful?

Solution

You can do it like this

 <a id="a3" href="http://stackoverflow.com" onclick="a(this);">Link3</a>
 <a id="a4" href="http://google.com"  onclick="a(this);">Link4</a>
 <a id="a5" href="http://wikipedia.org"  onclick="a(this);">Link5</a>

   <script>
      function a(t) {
        var href = t.getAttribute("href");
        if(href==null || href=="") return;
        window.open(href,'_blank');
        t.removeAttribute("href");
      }
   </script>

OTHER TIPS

How about

window.onload=function() {
  document.getElementById("a1").onclick=function() {
    setTimout(function() {document.getElementById("a1").disabled=true;},10)
  }
}

You can do it through events using a class name as an indicator

http://jsfiddle.net/pyQV2/

In this example I added every link a class, just to indicate the function to target it. Then, on page load I attach an onclick event to each link.

var links = document.getElementsByClassName('notclicked');

for (var i=0; i<links.length; i++) {
    links[i].onclick = function(e) {
        if (e.target.className == 'notclicked')
            e.target.className = 'clicked';
        else {
            if (e.preventDefault)
                e.preventDefault();
            else /* for IE */
                e.returnValue = false;
        }
    }
}

If it has the old class, just change it for future clicks. If it has the new class, just stop the event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top