Search code examples
javascriptjquerybrowser-historyhtml5-history

Forward button not working when using history and pushState/currentState on modal


I'm using history and pushState/currentState to:

  1. Change the URL when the modal is fired.
  2. If back button or modal close button is pushed, close the modal and go back to the previous URL.
  3. 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');
        }
    });

And here is a Fiddle.

Any help would be greatly appreciated. Thank you so much.


Solution

  • There are 2 apparent issues in your code:

    1. 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

    2. 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.