Reputation: 2459
I want to store a modal in a variable and then show the modal when a user clicks a button. I tried this but nothing happens when I click the button and there is no console error.
$( '.outlet' ).on('click', function(e) {
e.preventDefault();
var prodID = $(this).data('id');
var modal = `
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<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>
`;
$(modal).show();
});
Upvotes: 1
Views: 77
Reputation: 14870
You have to bind the modal
to the DOM, to make it visible. In your code the HTML of your modal
variable is not in the DOM, and that's why it is not displayed.
like show here:
$("body").before(modal).show();
Althought you won't need show()
since your attaching the HTML to the DOM with the before
function (except it the HTML code has a style property set to display:none
or you want a animation or ...).
Here the working example. I added some HTML to make the Example run.
$( '.outlet' ).on('click', function(e) {
e.preventDefault();
var prodID = $(this).data('id');
var modal = `
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<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>
`;
console.info("IN THE CLICK FUNCTION");
$("body").before(modal);
$(".modal").show();
});
.modal {
margin:50px;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 99;
display: none;
overflow: hidden;
-webkit-overflow-scrolling: touch;
outline: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button class="outlet">test</button>
</body>
Upvotes: 2