I have a nested div with 'additional information' inside.
When the div is clicked, it expands to show the 'additional information'.
To prevent closing when clicking on the text within the 'additional information', I used .stopPropagation()
, but the collapse still occurs if the borders or other areas are clicked.
I came across a post on Stack Overflow that was similar to what I needed (link), but couldn't quite get it to work as required.
Here is a codepen example (link) of my objective.
$('#collapsDiv').on('show.bs.collapse', function( event ) {
event.stopPropagation();
console.log('Only happen when outter div is opened');
})
$('#collapseDiv').on('hide.bs.collapse', function( event ) {
event.stopPropagation();
console.log('Only happen when outter div is collapsed');
})
$('#additionalDiv').on('click', function( event ) {
event.stopPropagation();
})
$('#collapseDiv').click(function(e) {
if (e.pageY > $(this).offset().top + $(this).height()) {
// bottom was clicked
console.log('bottom clicked!');
e.stopPropagation();
} else {
// up of the div was clicked
console.log('top clicked');
}
});
#collapseDiv {
cursor:pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/js/bootstrap.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div id="collapseDiv" class="alert alert-warning" data-toggle="collapse" href="#additionalDiv" role="button" aria-expanded="false" aria-controls="additionalDiv">
This Div shows by default - I used an alert to make it more visually obvious. Only this part should remain clickable. The hidden stuff should not be clickable. A bonus would be having the lower portion not have a pointer!
<div id="additionalDiv" class="collapse">
<div class="other-stuff">
<h2>This stuff should not be clickable</h2>
<p>There may be paragraphs here a user might want to copy/paste!</p>
<p>In a perfect world - even the bottom / sides would not trigger the collapse. This would only be collapsed by clicking the original div area.</p>
</div>
</div>
</div>
</div>
Although it seems to be functioning, clicks at the bottom can still cause the collapse - how do I extend this behavior to avoid clicks on the sides too?
On a side note, there appears to be a very small row at the bottom that triggers the collapse when clicked.