Reputation: 51
I have two modals I want to show when right fragment is in the URL, so domain.com#steg2
loads modal #steg2 and domain.com#steg3
loads modal #steg3.
My script:
$(function() {
if (window.location.hash.indexOf("steg2") !== -1) {
$("#steg2").modal();
}
if (window.location.hash.indexOf("steg3") !== -1) {
$("#steg3").modal();
}
});
This is how my modals are buildt:
<div class="modal fade" id="steg2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal fade" id="steg3" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
Both modals are on same page/URL. What am i doing wrong? Site is using bootstrap 3 and jQuery.
Upvotes: 1
Views: 4006
Reputation: 51
After some trials I found this code to do the work:
<script type="text/javascript">
jQuery(document).ready(function($) {
var target = document.location.hash.replace("#", "");
if (target.length) {
if(target=="steg1"){
$('#steg1').modal('show');
}
else if(target=="steg2"){
$('#steg2').modal('show');
}
else if(target=="steg3"){
$('#steg3').modal('show');
}
}
else{
}
});
</script>
Upvotes: 4
Reputation: 253308
I'd suggest:
function hashModal () {
var stegs = ['steg2','steg3'],
hash = window.location.hash,
stegAt = stegs.indexOf(hash.replace('#','');
if (stegAt > -1) {
$(hash + '.modal').modal();
}
}
$(document).on('ready hashchange', hashModal);
References:
on()
.Upvotes: 1
Reputation: 11210
First get the hash from the url with window.location.hash
. That value will have a # prepended to it. Then you can use it directly as a jquery selector.
var hash = window.location.hash;
if(hash != '') {
$(hash).modal();
}
Upvotes: 0