Bootstrap 3 close Modal when you press the back button

I just want to create a modal page that behaves the same way, either by clicking the browser back button or the close button inside the modal file using boot file 3. I found a script that does this, but there is a problem. let's say I start with google.com, go to this mod page, and then click β€œModal!”., then press the return button in the browser, it will close the modal mode, if I click the β€œBack” button again, it will return me to google .com (all is well). But this time, if I open the modal page and close the modal, using the close button instead. But now I will need to press the back button twice to return to google.com. If I open and close the modal using the close button inside the modal form, for example 10x. I found that I have to press the back button 10 more times to return to google.com. How to solve this problem? TIA

<!--html, bootstrap 3.2.0--> <div class="modal fade" id="myModal" tabindex="-1" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-body"> <p>If you press the web browser back button not the modal "close" button, the modal will close and the hash "#myModal" will be removed for the URL</p> </div> <div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div> </div> </div> </div> <!--jquery--> $('#myModal').on('show.bs.modal', function (e) { window.history.pushState('forward', null, '#modal'); }); $('#myModal').on('hide.bs.modal', function (e) { //pop the forward state to go back to original state before pushing the "Modal!" button }); $(window).on('popstate', function () { $('#myModal').modal('hide'); }); 

jsfiddle source

+5
source share
3 answers

I have found a solution. Feel free to post any other elegant solutions.

 $('#myModal').on('hide.bs.modal', function (e) { if(location.hash=='#modal')window.history.back(); }); $(window).on('popstate', function (event) { //pressed back button if(event.state!==null)$('.modal').modal('hide'); }); 
0
source

You can use the following code to simply get rid of the modal window that is open and not accidentally go to the previous browser page.

 //When ever the modal is shown the below code will execute. $(".modal").on("shown.bs.modal", function() { var urlReplace = "#" + $(this).attr('id'); history.pushState(null, null, urlReplace); }); // This code gets executed when the back button is clicked, hide any/open modals. $(window).on('popstate', function() { $(".modal").modal('hide'); }); 
0
source

When a button is pressed, a pop-up window will appear.

 $(document).ready(function(){ $(".popup-btn").click(function () { location.hash = "popup"; $(".popup-panel").show(); }); }); 

When you change the location, it will be hidden:

 $(window).bind('hashchange', function () { if (location.hash == null || location.hash == "") { $(".popup-panel").hide(); } }); 
0
source

Source: https://habr.com/ru/post/1258965/


All Articles