Skip to content

Bootstrap 4 – Avoid modal closing for on-screen click

In rails 4, I am using bootstrap plugin. When I am using modal feature there is close event issue which I need to solve. When modal opens, it should get close when I click on ‘x’ icon or ‘Esc’ button otherwise it should be open always. Right now when I click on the screen which excludes the modal form area it will get close.

In main.erb,

<div class="modal fade" id="main-lightbox-container" tabindex="-1" role="dialog" aria-labelledby="main-lightbox-container" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
    </div>
  </div>
</div>

In form.js.erb,

var content = "<%= escape_javascript(render(:partial=>"form", :locals=>{:user=>@user})) %>";
var container = $('#main-lightbox-container');
container.find('.modal-content').html(content);
container.modal({});

Here I am loading modal form via ajax request. How can I fix this on-screen click issue? Please help me.

Answer

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js">    </script>

<div data-toggle="modal" data-target="#modalid">Open</div>  
<div class="modal fade" id="modalid" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog">
<div class="modal-content">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
    </div>
    <div class="modal-body" style="background-color: #F0F0F0">
    Content
    </div>
</div>
</div>