0

So I want to handle the Bootstrap modal close/dismiss event. I have only ever been able to find the JQuery version on the interweb. How do we do this with native javascript?

I tried:

document.querySelector('#modal').addEventListener('hidden.bs.modal', onClick);

Of course, it didn't work. Does anyone have the knowledge and care to show me how? Thanks.

Tom
  • 15,781
  • 14
  • 69
  • 111
  • @Dai sorry, corrected the code. Yeah, besides the point. It doesn't seem to work as i mentioned. – Tom Jun 07 '20 at 11:56
  • Bootstrap has jQuery as a dependency though, so this might not be possible in the first place. Can I ask why you want to do this? –  Jun 07 '20 at 12:05
  • Tbh, You are correct. I am just trying not to use JQuery because I pretend to *look* more hardcore. XD anyway, I am getting close, might post an answer to my own question later. – Tom Jun 07 '20 at 14:03
  • To catch a jQuery `trigger()`-ed event you need a jQuery listener, as DOM Event API doesn't get notified about them (jQuery events are not `dispatch()`-ed). React, Vue, Angular or coreUi Bootstrap javascript replacements are dispatching regular DOM events, but jQuery is not. – tao Jun 08 '20 at 01:12
  • You're trying to detect a jQuery triggered event using `addEventListener`. Not possible. Only jQuery can detect a jQuery event, as jQuery events are not DOM Events. The answer I linked explains this in detail. If you have a better answer please post it on the question yours duplicates. – tao Jun 08 '20 at 03:35
  • @tao Done. Posted my answer to the other question. My question was not duplicated. I was the one asking and not accepting JQuery as an answer. Anyway, you can see my solution there, less than 20 lines of code including brackets. – Tom Jun 08 '20 at 03:51
  • @Tom +1-ed it (for TOTB), although I don't find it fully appropriate: it doesn't detect the `hidden.bs.event` *per-se*, which is what you said you wanted. It detects changes to the `style` attribute and, depending on use-case, yours might trigger false positives. Also, you have no support for start and end of transition, as Bootstrap does. In the end, you're writing a lot of code to act like jQuery (the elephant) was not in the room, but it's the elephant that triggers what you're trying to detect. Angular, React, Vue and CoreUI Bootstrap wrappers: all trigger native DOM events for this. – tao Jun 08 '20 at 12:41
  • Thanks. I am aware of the elephant in the room you mentioned. this is what really happened in my production code `$('this.id).on('hidden.bs.modal', onHide);` I am just doing native js only to challenge myself. Silly, I know, but hope that will inspire anyone out there who find the piece of native js useful. Cheers – Tom Jun 10 '20 at 00:53

0 Answers0