I am having trouble to find the clicked anchor element in the collapse event using Bootstrap 3.3.4.:
$('.collapse').on('show.bs.collapse', function (e) {
// Get clicked element that initiated the collapse...
});
I need this because I'd like to prevent collapsing if the clicked element has a certain data attribute. Another option would be to hook in by using .on('click', function())
, however there are other events that occur on click that need to run so this seems a no-go to me. Searching in the DOM for the closest anchor or something similar won't work as well since there are multiple anchors next to eachother.
Just add data-toggle="collapse" and a data-target to the element to automatically assign control of one or more collapsible elements. The data-target attribute accepts a CSS selector to apply the collapse to. Be sure to add the class collapse to the collapsible element.
The . collapse class indicates a collapsible element (a <div> in our example); this is the content that will be shown or hidden with a click of a button. To control (show/hide) the collapsible content, add the data-toggle="collapse" attribute to an <a> or a <button> element.
How it works. The collapse JavaScript plugin is used to show and hide content. Buttons or anchors are used as triggers that are mapped to specific elements you toggle. Collapsing an element will animate the height from it's current value to 0 .
A <button> or <a> can show and hide multiple elements by referencing them with a selector in its href or data-bs-target attribute. Multiple <button> or <a> can show and hide an element if they each reference it with their href or data-bs-target attribute. Toggle first element Toggle second element Toggle both elements.
Since my case featured multiple anchors next to eachother (viz. disregarding regular Bootstrap structure), I ended up searching for the clicked anchor by using the collapsing div's ID:
$('.collapse').on('show.bs.collapse', function (e) {
// Get clicked element that initiated the collapse...
clicked = $(document).find("[href='#" + $(e.target).attr('id') + "']")
});
This is working in Bootstrap 4.2
$(".collapse").on('shown.bs.collapse', function(e){
$clickedElement = $($(e.target).data('bs.collapse')._triggerArray);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With