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");
.this
in this context refers to thewindow
object because thepopstate
event is registered on thewindow
. Thewindow
doesn't have adata-modal
attribute sodataModal === undefined
You're not saving the modal id anywhere when you
pushState
in 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.dataModal
to get the modal id.