I'm using history and pushState/currentState to:
- Change the URL when the modal is fired.
- If back button or modal close button is pushed, close the modal and go back to the previous URL.
- If modal is fired, closed, and the forward button is pushed, re-open the modal and go to the modal URL.
All is working EXCEPT 3. I have this JS in there but it doesn't seem to work:
window.addEventListener('popstate', function (e) {
var state = history.state;
// back button pressed. close popup
if (!state) {
$(".modal").css({ "display": "none" });
$('body').css('position', 'relative');
}
else {
dataModal = $(this).attr("data-modal");
$("#" + dataModal).css({ "display": "flex" });
$('body').css('position', 'fixed');
}
});
Any help would be greatly appreciated. Thank you so much.
There are 2 apparent issues in your code:
dataModal = $(this).attr("data-modal");.thisin this context refers to thewindowobject because thepopstateevent is registered on thewindow. Thewindowdoesn't have adata-modalattribute sodataModal === undefinedYou're not saving the modal id anywhere when you
pushStatein the modal trigger event.Possible solution
Try doing something like
history.pushState({dataModal: dataModal}, title, url);in the modal trigger event. Then in the popstate event you can dovar dataModal = e.state.dataModalto get the modal id.