user2449079
user2449079

Reputation: 3

Disable CSS link for 1 second after it has been clicked

I'm trying to have a CSS link disabled for 1 second after it has been clicked.

I have tried this without success;

In the header:

<script type="text/javascript">
$(function() {
    $("#link").click(function() {
        $("#link").attr("disabled", "disabled");
        setTimeout(function() {
            $("#link").removeAttr("disabled");      
        }, 2000);
    });
});
</script>

Html:

<a href="#" class="link">the link text</a>

CSS:

.link:diabled {
some values here.. }

Upvotes: 0

Views: 264

Answers (4)

Josh Bedo
Josh Bedo

Reputation: 3462

I think this approach works better. The other allows you to click the link multiple times and mess up the setTimeout this unbinds the event and then re-attaches the event after the setTimeout ex: double click the link

$(".link").click(linkBind);
function linkBind(){
    var $this = $(this);
        $this.addClass('disabled');
        $this.unbind('click');
        setTimeout(function() {
            $this.removeClass('disabled');
            $this.bind('click', linkBind);
        }, 2000);
}

$(document).on('click', '.disabled', function (e) {
    e.preventDefault();
});

http://jsfiddle.net/PaYcc/1/

Upvotes: 0

itz2k13
itz2k13

Reputation: 159

'link' is a class and you are using it as ID. Do $('.link') instead of $('#link').

Upvotes: 3

Explosion Pills
Explosion Pills

Reputation: 191729

There are quite a few problems here:

  1. You are using # (the ID selector), but your html is using classes.
  2. <a> does not have a disabled attribute
  3. If it did, you would probably want to use .prop instead of .attr
  4. If you change code to use classes, $(".link").prop("disabled", true) would affect all anchors, so you should probably use this.
  5. Because disabled does not exist for <a>, the :disabled selector does not seem to work for CSS.

A working solution would be something like this:

$(".link").click(function() {
    var $this = $(this);
    $this.addClass('disabled');
    setTimeout(function() {
        $this.removeClass('disabled');
    }, 2000);
});

$(document).on('click', '.disabled', function (e) {
    e.preventDefault();
});

http://jsfiddle.net/ExplosionPIlls/PaYcc/

Upvotes: 3

bwoebi
bwoebi

Reputation: 23777

You have a class="link", but with $("#link") you are addressing the id called link.

So write $(".link") everywhere instead of $("#link").

By the way: with .link:disabled you won't address the link as this only works on inputs and buttons. If you need to address it, use .link[disabled="disabled"] { ... } or even better add a class to it called disabled_link and then do in CSS .disabled_link { ... }.

Upvotes: 4

Related Questions