Open a Bootstrap Modal automatically from an external link
Solution 1
You can use the hastag to decide the content to show. For example,
JS
$(document).ready(function () {
var target = document.location.hash.replace("#", "");
if (target.length) {
if(target=="option1"){
showModal("title1","content1");
}
else if(target=="option2"){
showModal("title2","content2");
}
}else{
showModal("no title","no content");
}
function showModal(title,content){
$('#myModal .modal-title').html(title);
$('#myModal .modal-body').html(content);
$('#myModal').modal('show');
}
});
HTML - Bootstrap modal code
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">...</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
this will show content for option1
http://jsfiddle.net/fFcS2/show/#option1
this will show content for option2
http://jsfiddle.net/fFcS2/show/#option2
the code
Solution 2
Sorry for the delay in coming back... your solution worked 100%. Just as I already had multiple modals, i modified the code like this:
<script type="text/javascript">
jQuery(document).ready(function($) {
var target = document.location.hash.replace("#", "");
if (target.length) {
if(target=="modal1link"){
$('#modal1').modal('show');
}
else if(target=="modal2link"){
$('#modal2').modal('show');
}
else if(target=="modal3link"){
$('#modal3').modal('show');
}
}else{
}
});
</script>
Solution 3
If anyone comes here looking for a dynamic solution (where you don't have to pre-define modal ids), here you go:
$(document).ready(function() {
var url = window.location.href;
var modalToOpen = url.substring(url.indexOf("#"));
if(window.location.href.indexOf(modalToOpen) != -1) {
$(modalToOpen).modal("show");
}
});
This script grabs the current URL, finds the id after the hash in the URL, and then shows the modal with corresponding id.
Comments
-
stankobrin about 2 years
I have a page with 4-5 different modals attached to it. Each with a unique #value (obv). I am trying to find a way to link to these individual modals' from an external source (in this case an HTML email).
For example:
"Click here to view directions" in the email needs to link to -->> www.myurl.com/#directions
the #directions piece should trigger the : function on page load and have the modal automatically open.
Is this possible or am i only dreaming?
-
Daniel over 4 yearsThis works great except if you also need to jump within same page, does not work for external links only. If any internal hrefs breaks other jquery plugins like easing/smooth scroll, wow, etc.