Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the clicked element in Bootstrap collapse event?

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.

like image 981
Propaganistas Avatar asked Jun 02 '15 12:06

Propaganistas


People also ask

How do I collapse an element in Bootstrap?

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.

How do you collapse a div on a button click?

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 does collapse work in Bootstrap?

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 .

What is BS Bootstrap?

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.


2 Answers

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') + "']")
});
like image 168
Propaganistas Avatar answered Oct 09 '22 08:10

Propaganistas


This is working in Bootstrap 4.2

$(".collapse").on('shown.bs.collapse', function(e){
    $clickedElement = $($(e.target).data('bs.collapse')._triggerArray);
});
like image 32
user3464977 Avatar answered Oct 09 '22 09:10

user3464977