Prevent input checkbox from toggling <details>
Welcome to the incompatible world of browsers! :D
First of all, you should consider working with the click
event instead of the change
event, because if user clicks on a checkbox, first the click
event is triggered and then change
event, which means the click
event is responsible for the toggle behaviour and again not the change
event.
So, on both Chrome and Firefox, the click
event for special elements such as input
, button
, textarea
that lies in the summary
element bubbles up to the parent details
element, which is a normal behaviour, however the interesting thing is that the click
event is apparently only ignored in Chrome and not processed further, so that the details
element is not toggled. You can try it with another element, i.e. button
, on Chrome, and you will observe no difference. Firefox on the other hand just toggles it regardless of the type of element.
So, to overcome this problem, (with a little help of CSS) you can try it with a ghost checkbox
element, so to speak, that is absolutely positioned, thus not part of the normal document flow. It's invisible and most importantly operates the state of the visible checkbox by staying on top of it and handling the click
event in the first place, like so:
P.S. Works both on Firefox and Chrome - tested.
$('input.ghost-checkbox').click(function(e) {
$(this).next().prop('checked', !$(this).next().prop('checked'));
return false;
});
.ghost-checkbox {
opacity: 0;
position: absolute;
z-index: 2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<details>
<summary>
<span style="overflow: hidden">
<input type="checkbox" class="ghost-checkbox">
<input type="checkbox">
</span>
</summary>
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse finibus bibendum lorem, vitae efficitur felis mattis vitae. Sed mattis tristique rutrum. Morbi a placerat purus, et pulvinar risus. Vivamus accumsan sapien et nisi vulputate blandit. Aenean nec consectetur nulla. Nunc efficitur tincidunt placerat. Vivamus blandit est lectus, ut fermentum velit vulputate ut. Morbi elementum sem massa, eleifend laoreet dui tristique quis. Nulla mi dolor, consectetur blandit fermentum quis, tempor id nisi. Phasellus vel lobortis enim, id blandit turpis. Nullam dapibus feugiat risus eu pharetra. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam enim justo, pharetra sit amet urna sed, ultricies tempor nibh.
</div>
</details>