0

I have the following code that I found here https://stackoverflow.com/a/60187153/16383273

function handleBackPress(event) {
  event.preventDefault();
  event.stopPropagation();
  $('.modal').modal('hide');
  $('.modal-backdrop').remove();
}

var closedModalHashStateId = "#modalClosed";
var openModalHashStateId = "#modalOpen";

window.location.hash = closedModalHashStateId;

$(window).on('popstate', this.handleBackPress);
document.addEventListener("backbutton", this.handleBackPress, false);

$('.modal').on('show.bs.modal', function(e) {
  window.history.pushState('forward', null, './'+openModalHashStateId);
});

$('.modal').on('hide.bs.modal', function(e) {
  window.history.back();
});

I am using this code to close bootstrap modals using phone's back button. However, I found an issue here. This code closes all the modals open at once. This is irritating from the user's point of view. What I want to do here is that I want to close the bootstrap modals one by one. With the first back button clicked it should close the most recent one. The other modals should still remain active and displayed. On further clicking of back buttons it should keep closing further modals as per their opening sequence or as per which is currently displayed on the screen. How can I do this?

Relaxing Music
  • 452
  • 4
  • 13
  • Using a selector like `$('.modal')` will select all elements with that class. So you cna use `.get()` to select the last item. `$('.modal').get($('.modal').length - 1)` or `$('.modal:last')` – Twisty Sep 20 '21 at 20:54
  • @Twisty not working... After adding either of them now even single modal isn't closing. – Relaxing Music Sep 20 '21 at 21:11
  • Please provide a Minimal, Reproducible Example: https://stackoverflow.com/help/minimal-reproducible-example – Twisty Sep 20 '21 at 21:17
  • It's already too minimal and reproducible. I can't make it more smaller. The code given is very small and all required ones. Can't slice it further. Also, details are clearly explained. – Relaxing Music Sep 20 '21 at 21:19
  • I am unable replicate the issue with the provided code. There is no HTML only JavaScript. I don't know what libraries are involved or CSS, so this is no where near a Minimal, Reproducible Example. – Twisty Sep 20 '21 at 21:22
  • @Twisty I have created a pen here https://codepen.io/shreyk99/pen/ExXLRbj . Please open it (preferably using your MOBILE PHONE browser but desktop browser will also do). Launch Modal and then launch inside modal within that modal. Now click on the back button of your phone. It closes these modals. However, you will see that it closes both the modals open. I want it to close the 2nd modal first then the first one serially when the back button is pressed. I hope this pen will help with the minimal reproducible thing :) – Relaxing Music Sep 20 '21 at 21:49

0 Answers0