Lotus_8 Lotus_8 - 3 months ago 12
Javascript Question

Bootstrap modal close issue

I am trying to work the bugs out of my

modal
. I am using
Bootstrap
,
Angular
and
ng-Route
. I recently noticed on
mobile
(and then on desktop) when I push the back button with the
modal
open it leaves a gray overlay and you cannot
click
anything. So the solution I found that partially fixes the problem is to add this script:

$(".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');
});


This works great then the user
presses
the
back button
however when the user closes the
modal
by clicking outside of the modal or hitting escape the
urlReplace
remains in the
browser
address bar. I want to get it to change back to the previous when ever the
modal
is closed.


If that issue cannot be resolved I at least would like this other issue to be fixed which is this: When the user closes the
modal
by clicking outside or hitting escape the
urlReplace
remains in the
browser
address which is fine but when the user then goes to
click
a link in my
nav bar
it doesn't take them to the link it goes to a blank page with the
urlReplace
still in the address bar and then I can
click
a link in the
nav bar
again and it will go to the proper link which I find strange not sure how to resolve this issue.

Any ideas or insights into this would be awesome!

Answer

Just add a handler to watch for the modal close event, then push a new history with the hash removed:

$(".modal").on("hidden.bs.modal", function()  { // any time a modal is hidden
    var urlReplace = window.location.toString().split('#', 1)[0]
    history.pushState(null, null, urlReplace); // push url without the hash as new history item
});
Comments