user3214661
user3214661

Reputation: 17

Disable link, after it is clicked

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?

Upvotes: 0

Views: 980

Answers (3)

Gil
Gil

Reputation: 1804

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.

Upvotes: 0

Paramore
Paramore

Reputation: 1313

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>

Upvotes: 0

mplungjan
mplungjan

Reputation: 178011

How about

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

Upvotes: 0

Related Questions