I want to open a modal when I click on a link.
Unfortunately I couldn't change the HTML of the link. I could only change the content of href
.
Like this:
<a href="#Modal">Open modal</a>
I could not add data-attributes or any other HTML.
In the docs I found a way to open the modal via JavaScript. I added this code to my site:
$('#Modal').modal();
It works but the modal opens immediately after the page loads. I need it to open after I click on the link.
Is there a way to do this?
Here's my modal:
<div class="modal" id="Modal" tabindex="-1" role="dialog" aria-labelledby="ModalTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<p class="h5 modal-title" id="ModalTitle">Modal Title</p>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
<div class="modal-body">
Content
</div>
</div>
</div>
</div>
Trigger click event on a[href$="#Modal"]
.
$('a[href$="#Modal"]').on( "click", function() {
$('#Modal').modal('show');
});
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<!-- Trigger the modal with a button -->
<a href="#Modal" class="btn btn-info btn-lg">Open modal</a>
<!-- Modal -->
<div id="Modal" 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>
EIDT: changed myModal to Modal
Try this
<!-- Trigger the modal with a button -->
<a href="#" class="btn btn-info btn-lg">Open Modal</a>
<!-- 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>
$('a').on( "click", function() {
$('#myModal').modal('show');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With