0

I'm trying to get the caller element from inside of an event listener function of jQuery using Bootstrap3.

Code:

jQuery(MoreOptionsCollapse).on('show.bs.collapse', function(event){
    console.log(this, event, event.target);
});

Console: enter image description here

The problem is that this and event.target are the MoreOptionsCollapse element and what I want is the button that triggered the show.bs.collapse event.

Any help would be appreciated c:

Community
  • 1
  • 1
James
  • 679
  • 1
  • 8
  • 22
  • 1
    Related: https://stackoverflow.com/questions/30596773/how-to-get-the-clicked-element-in-bootstrap-collapse-event Neither ranking answer there is a perfect match, though. – isherwood Apr 25 '19 at 16:12
  • You might just use a click listener on the triggering elements themselves. – isherwood Apr 25 '19 at 16:13
  • I thought so too at the beginning but there will be more buttons triggering the same event, and what I want to do is change the caller element's text depending on the state of the collapse, wouldn't want to do messy code just for that :/ – James Apr 25 '19 at 16:15
  • 1
    Understood. If you can switch to `shown.bs.collapse` you're golden. Otherwise it's probably not that difficult to get the collapse element associated with the trigger and check its state (`.in`). – isherwood Apr 25 '19 at 16:16
  • well, you know that the original event target will be the element that was actually clicked... which will at the very least be inside the button, if it isn't the button itself. You could use traversal methods to go from there to your button if it isn't the button.. – Kevin B Apr 25 '19 at 16:24
  • @isherwood Got it solved, thanks! – James Apr 25 '19 at 16:53

1 Answers1

1

As pointed out by @isherwood in the comments and in this post, you need to add a listener to the shown.bs.collapse instead of show.bs.collapse so that the jQuery element's data() can make time for bs.collapse to be indexed with the caller element set in $trigger key.

jQuery(MoreOptionsCollapse).on('shown.bs.collapse', function(){
    var triggerButton = jQuery(this).data('bs.collapse').$trigger[0];

    triggerButton.set('text', 'Some other text after element toggled');
});
James
  • 679
  • 1
  • 8
  • 22