Here in this post we will learn how to make a bootstrap modal open inside a div.
For example
We have the following HTML Structure
<div> <button id="btn">Open Modal</button> <div class="red block"> </div> <div class="blue block"> </div> </div>
Now what we need to do is to open a bootstrap modal inside the blue div on the click of a button.
So to do so follow the steps given below :-
- Write the HTML code for the bootstrap modal inside the blue div .
<div> <button id="btn">Open Modal</button> <div class="red block"> </div> <div class="blue block"> <!-- Modal --> <div id="myModal" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h4 class="modal-title">Modal Header</h4> </div> <div class="modal-body"> <p>Some text in the modal.</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> </div>
- Write the following Javascript Code
$(document).ready(function(){ $("body").on("click","#btn",function(){ $("#myModal").modal("show"); //appending modal background inside the blue div $('.modal-backdrop').appendTo('.blue'); //remove the padding right and modal-open class from the body tag which bootstrap adds when a modal is shown $('body').removeClass("modal-open") $('body').css("padding-right",""); }); });
- Write the following CSS for it
.red { background-color:red; } .blue { background-color:blue; position:relative;// so that .modal & .modal-backdrop gets positioned relative to it } .block { width:100%; height:200px; } .modal, .modal-backdrop { position: absolute !important; }
- That’s It
You can also visit this fiddle for a quick working demo.
Logic Behind The Scene
To show a bootstrap modal inside a div the logic behind the above code is to append the HTML code of the modal as well as the modal-backdrop inside that specific div(blue div whose position is relative) and then making the CSS for modal and modal-backdrop to position:absolute so that the modal and its background gets positioned relative to its parent .
For those who don’t know what a modal-backdrop is, the answer is that its a div appended whenever a bootstrap modal appears by the modal plugin so as to provide a click area for dismissing shown modals when clicking outside the modal.
In short its that translucent dark background behind a bootstrap modal.
You can also check our available Magento 2 extensions.
6 comments
Hello Jahan,
Happy to know that this was helpful!
Regards,
Team Webkul.
🙂
Thanks for the appreciation.
With Regards,
Webkul Team
i found new idea for that just add Style after modal-dialog Class
Ex :