Search code examples
twitter-bootstrap

Change where bootstrap "modal-open" class is assigned to instead of the body


Currently

modal-open

is assigned to the body when the modal is opened. How do i change where the class is added to instead of the body.

Thanks for any help.


Solution

  • You have to change js that adds modal-open. It's a bit strange as behaviour, anyway you can do it softly or brutally.

    Softly: intercept modal click for show and remove class to body adding to another element:

    // Modal is first added to the body element and then removed and added to another element

    $('#myModal').on('shown.bs.modal', function (e) {
      $('body').removeClass('modal-open');
      $('#myCustomElement').addClass('modal-open');
    })
    

    and then intercept also the close of the modal and add an execution of a second remove:

    $('#myModal').on('hidden.bs.modal', function (e) {
       $('#myCustomElement').removeClass('modal-open');
    })
    

    Brutal method, to avoid that modal-open it's unnecessary added to body element: go in TwitterBootstrap directory > js Open modal.js Search for modal-open , you will find (on version 3.2.0):

    in

     Modal.prototype.show
    

    you'll find

    this.$body.addClass('modal-open')
    

    in Modal.prototype.hide you'll find

    this.$body.removeClass('modal-open')
    

    you have to change the target of addClass and removeClass and replace those instructions, if you have a fixed element it's enough simple (Ex: $('#myFixedElement').addClass('modal-open'), if it's a dynamic element it's complex and you'll have again to intercept Show function to add a global var in js to let modal.js know and read your target element. However you can also change the signature of those functions but i don't really suggest you to do that, basically you'll make your code too hard to maintain.