I've just spent a couple of days trying to fix a problem with jQuery and Bootstrap modals on a Joomla component page.

I was updating the xbCulture components - adding site pages preview modal popups (using an eycon  as the modal trigger) and changing the arrangement to use ajax direct loading of the modal-content div. On the admin pages I had been saving or re-loading the page when the modal closed, but I didn't really want to do that is it looses the page context.

 

All is fine the first time a modal is opened and closed, but every subsequent time a modal is opened an additional modal-backdrop div gets added and then only the first one is cleared when the modal closes.

After much searching and finding various similar problems - none of whose solutions seemed to work for me. Some suggested that it was a bug in bootstrap and/or jQuery and updating to later versions fixed it - but that is not possible with J3 as jQuery and bits of bootstrap are embedded in the framework.

Finally I gave in and asked the question on stack exchange (where most of the pre-existing related questions with answers that don't work here can be found). One comment pointed at a previous question I hadn't seen - and there amongst the similar common non-working answers was one that gave me an idea.

Using jQuery's DOMNodeRemoved() event enables you to detect when the first modal-backdrop is removed by the closing modal, and then remove all the rest.

jQuery(document).on("DOMNodeRemoved",".modal-backdrop",function(){
    jQuery(".modal-backdrop").remove();
});

That is fine but you still have the multiple modal-background divs causing the background to go black once there are more than a couple overlaying each other.

So I wondered if there is a DOMNodeInserted() function that could be used to remove subsequent unwanted extra modal-backdrops after the first. Of course there is and with a bit of tinkering I discovered how to make it work.

jQuery(document).bind('DOMNodeInserted', function(e) {
    var element = e.target;
    if (jQuery(element).hasClass('modal-backdrop')) {
       alert('here we are');
    if (jQuery(".modal-backdrop").length > -1) {
            jQuery(".modal-backdrop").not(':first').remove();
        }
    }
});

Of course this isn't actually fixing the underlying problem that bootstrap is generating spurious extra modal-backdrops; it just fixes it when they appear.