Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle Bootstrap modal with URL and hash

I'd like to use URLs with hashes to call specific Bootstrap modals. In other words, a user is on page1 and clicks on a link to page2#hash and the #hash modal loads when page2 loads. I've tried so many variations based on what I've read in other Q/As, but nothing has worked. I'm not at all experienced with JS, so I'd appreciate some help!

Here's what I have:

Link on page1: <a href="/page2#myModal>

HTML on page2:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
  ...
</div>


Javascript on page2:

<script>
  if(window.location.hash) {
    var hash = window.location.hash;
    $("'" + hash + "'").modal('toggle');
  }
</script>


Incidentally, <a href="#" data-toggle="modal" data-target="#myModal"> works just fine to call the modal when the user is actually on page2.

like image 801
lacoder Avatar asked Jul 26 '14 05:07

lacoder


People also ask

How do I toggle a bootstrap modal?

To trigger the modal window, you need to use a button or a link. Then include the two data-* attributes: data-toggle="modal" opens the modal window. data-target="#myModal" points to the id of the modal.

How can I toggle modal in PHP?

Or, you could use: $(document). ready(function(){ // Here goes yor code });

What does data toggle modal do?

The data-toggle is an HTML-5 data attribute defined in Bootstrap. The advantage of using this is that, you can select a class or an id and hook up the element with a particular widget.


1 Answers

You are adding single quotes to your selector, selectors don't use quotes:

$("'" + hash + "'").modal('toggle');

should be

$(hash).modal('toggle');

Also you might not be waiting for the dom to be ready to use. If you do not have that script at the bottom of the page or at least below where your modal html is, it won't be found as it is not created yet.

<script>
  //shortcut for $(document).ready
  $(function(){
      if(window.location.hash) {
          var hash = window.location.hash;
          $(hash).modal('toggle');
      }
  });
</script>
like image 143
Patrick Evans Avatar answered Oct 04 '22 22:10

Patrick Evans