0

I have a div that has an icon in it, I add disabled property to the div and the click event still fires. So I went and created a copy of the div and changed the div to a button. Both have click events, yet the button won't fire when clicked on, but the div one will fire. Why is this, and how to I stop the click event firing when I click on the div?

I know that I can check for the disabled attribute during the click event, but wondering why I would have to do that and why the disabled doesn't work on a div

$('#btn').on('click', function() {
  alert("clicked");
});

$('#btn1').on('click', function() {
  alert("clicked");
});
#btn {
  cursor: pointer;
}

#btn[disabled] {
  cursor: not-allowed;
}

#btn1 {
  cursor: pointer;
}

#btn1[disabled] {
  cursor: not-allowed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" />

<div id="btn" class="disabled" disabled>
  <i class="fa fa-plus"></i>
</div>

<button id="btn1" class="fa fa-undo" disabled>
click
</button>
Chris
  • 2,953
  • 10
  • 48
  • 118
  • 1
    The answer is all here I'd say - https://stackoverflow.com/questions/639815/how-to-disable-all-div-content -- they do even mention that disabled is not defined for div elements in the w3c spec. –  Apr 16 '20 at 18:26
  • 1
    Disabled isn't a valid attribute for a div – j08691 Apr 16 '20 at 18:30

3 Answers3

2

<div> does not have disabled property, you have to check if it is disabled when clicking.

$('#btn').on('click', function() {
  if (!$(this).prop("disabled"))
  alert("clicked");
});
MARSHMALLOW
  • 1,315
  • 2
  • 12
  • 24
Alen.Toma
  • 4,684
  • 2
  • 14
  • 31
1

You can make use of the following css to disable click on div element as div element doesn't have disabled attribute:

 pointer-events: none;
 cursor: default;

Hope this helps..thanks

1

The disabled attribute does not work on div. If you insist on not checking for the attribute, you can use the :not() selector.

$('#btn:not(.disabled)').on('click', function() {
  alert("clicked");
});

'#btn:not(.disabled)' looks for elements with id btn and without a disabled class.

MathCoder
  • 442
  • 3
  • 9