I'm using history and pushState/currentState to:
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 the window
object because the popstate
event is registered on the window
. The window
doesn't have a data-modal
attribute so dataModal === 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 do var dataModal = e.state.dataModal
to get the modal id.