Skip to content

Instantly share code, notes, and snippets.

@thedamon
Created February 28, 2014 17:59
Show Gist options
  • Save thedamon/9276193 to your computer and use it in GitHub Desktop.
Save thedamon/9276193 to your computer and use it in GitHub Desktop.
Cause back button to close Bootstrap modal windows
$('div.modal').on('show', function() {
var modal = this;
var hash = modal.id;
window.location.hash = hash;
window.onhashchange = function() {
if (!location.hash){
$(modal).modal('hide');
}
}
});
$('div.modal').on('hide', function() {
var hash = this.id;
history.pushState('', document.title, window.location.pathname);
});
@Angel-Glez
Copy link

This seemed to work for me:

 $(".modal").on("shown.bs.modal", function()  { // any time a modal is shown
    var urlReplace = "#" + $(this).attr('id'); // make the hash the id of the modal shown
    history.pushState(null, null, urlReplace); // push state that hash into the url
  });

  // If a pushstate has previously happened and the back button is clicked, hide any modals.
  $(window).on('popstate', function() { 
    $(".modal").modal('hide');
  });

It works fine for me too but I had the problem with 2 or more visible modals in same page, when I wanted to close the top modal, all modal get close, so I changed a little bit the $(window).on('popstate', function() function and fully works.
This is my first conttribution, hope this helps.

  $(window).on('popstate', function() { 
     //$(".modal").modal('hide');
     if ($(".modal:visible").length){                                 // validate that there are visible modal
         $(".modal").eq($(".modal:visible").length-1).modal('hide');  // hide only the last model opened
     }
  });```

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment