Toggle Bootstrap modal with URL and hash

18,036

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>
Share:
18,036
lacoder
Author by

lacoder

Updated on July 27, 2022

Comments

  • lacoder
    lacoder almost 2 years

    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.

  • lacoder
    lacoder almost 10 years
    Thanks, Patrick. I moved the js to the bottom of the page, and replaced my js with yours, and it still didn't work. No idea why...
  • Patrick Evans
    Patrick Evans almost 10 years
    Are you getting errors on your console? Or do you have a live example that can be viewed?
  • lacoder
    lacoder almost 10 years
    Got it! The console showed "Uncaught TypeError: undefined is not a function," and it was referencing the line with $(hash).modal('toggle');. So I did some digging and changed our jquery from 1.11.1 to 2.1.1. Then the code you provided worked! Many thanks, Patrick.
  • Patrick Evans
    Patrick Evans almost 10 years
    Note that using 2.x series does not support the older browsers (just mentioning that in case you have to support them). The url that you were using for the 1.11.1 was probably wrong (typo in the url etc).
  • lacoder
    lacoder almost 10 years
    You're absolutely right. We originally copied the jQuery link from Bootstrap's basic template, and that wasn't working. However, I just went back and copied the link for 1.11.1 directly from Google's hosted libraries page, and that did work. On the money.