Home > Blockchain >  Get clicked element on show.bs.collapse with bootstrap 4 Collapse
Get clicked element on show.bs.collapse with bootstrap 4 Collapse

Time:10-27

I have a serie of buttons, all callapsing the same panel. I'm trying to get the clicked element that opened the panel so I can dynamically inject some data in the panel.

I need, if possible, to get the element on the show.bs.collapse event so I can inject the data before the panel is displayed

here is my html :

<div class='container'>
     <div class='buttons'>
          <a id='link-one' data-toggle='collapse' href='#panel' aria-expanded='false' aria-controls='panel'>Link One</a>
          <a id='link-two' data-toggle='collapse' href='#panel' aria-expanded='false' aria-controls='panel'>Link Two</a>
          <a id='link-three' data-toggle='collapse' href='#panel' aria-expanded='false' aria-controls='panel'>Link Three</a>
     </div>
     <div id='panel' class='panel collapse'>
    *dynamic content related to link triggered*
     </div>

</div>

I've found these posts about the question :

Bootstrap How to get element clicked to collapse

How to get the clicked element in Bootstrap collapse event?

Bootstrap modal relatedTarget is undefined

But unfortunately, none of them works nor gave me an answer.

I tried to find event.relatedTarget but there is no such things in the show.bs.collapse event

CodePudding user response:

I don't see that Bootstrap provides the clicked element either, so you can simply track it yourself and use it in the callback.

let currentButtonId;

$('.buttons a').click(e => {
  currentButtonId = e.target.id;
});

$('#panel').on('show.bs.collapse', e => {
  $('#panel').text(currentButtonId   ' was clicked');
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI N" crossorigin="anonymous">

<div class='container'>
  <div class='buttons'>
    <a id='link-one' data-toggle='collapse' href='#panel' aria-expanded='false' aria-controls='panel'>Link One</a>
    <a id='link-two' data-toggle='collapse' href='#panel' aria-expanded='false' aria-controls='panel'>Link Two</a>
    <a id='link-three' data-toggle='collapse' href='#panel' aria-expanded='false' aria-controls='panel'>Link Three</a>
  </div>

  <div id='panel' class='panel collapse'>
    *dynamic content related to link triggered*
  </div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>

  • Related