0

I am trying to add disabled class to bootstrap anchor button, but it does not work. I added it like below,

  1. jquery>js>html
  2. jquery>html>js

$(document).ready(function() {
  var fewSeconds = 5;
  
  $('#dis').click(function() {
    var btn = $('#dis');
    btn.addClass('disabled');
    // alert('works');
    
    setTimeout(function() {
      btn.removeClass('disabled');
    }, fewSeconds * 1000);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="/posts" id="dis" class="btn btn-light me-2 my-2 rounded-pill" type="button">Posts</a>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Hfyuu
  • 199
  • 1
  • 3
  • 11
  • 1
    Your question not clear. What's your purpose? U want anchor to be clicked but disable for next 5 second not to be clicked again ? – Bidzina Aivazashvili Jan 04 '21 at 08:37
  • Yes, I want to disable it for 5 seconds. – Hfyuu Jan 04 '21 at 08:47
  • 1
    The page is redirected after the `a` element is clicked, so what purpose are you expecting blocking the link after clicking it to have? The use will not be on the same page any more – Rory McCrossan Jan 04 '21 at 08:48
  • Ok, I was on localhost and I cant find the change as it is very fast. It works here. – Hfyuu Jan 04 '21 at 08:51
  • Does this answer your question? [jQuery disable a link](https://stackoverflow.com/questions/970388/jquery-disable-a-link) – Don't Panic Jan 04 '21 at 09:21

3 Answers3

0

Use preventDefault(); to disable the link.

$(document).ready(function() {
  $('.disabled').on("click", function (e) {
    e.preventDefault();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a href="https://stackoverflow.com/" class="disabled">Link</a>
Lundstromski
  • 1,197
  • 2
  • 8
  • 17
0

jQuery code to disable is

$('#dis).prop('disabled', true);

$(document).ready(function() {
  var fewSeconds = 5;
  
  $('#dis').click(function(e) {
    e.preventDefault();
    var btn = $('#dis');
    btn.prop('disabled', true);
    
    setTimeout(function() {
      btn.prop('disabled',false);
    }, fewSeconds * 1000);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="/posts" id="dis" class="btn btn-light me-2 my-2 rounded-pill" type="button">Posts</a>
Rajen Trivedi
  • 1,225
  • 2
  • 5
  • 10
0

Ok, I was on localhost and I cant find the change as it is very fast. It works here

Hfyuu
  • 199
  • 1
  • 3
  • 11