0

I have a simple pop-up contact form script written:

$(document).ready(function(){
    var popupButton = $("#contact-popup-button");
    var popupBox = $("#pop-up-contact");
    var popupBg = $("#pop-up-close-background");

    popupButton.on("click", function(){
        popupBox.addClass("slide-out");
        popupBg.fadeIn(200);
    });

    popupBg.on("click", function(){
        popupBox.removeClass("slide-out");
        popupBg.fadeOut(100);
    });

Basically when a button is clicked, a div appears and the space behind it gets foggy. If you press the space around the appeared div, it will dissapear. Now for mobile devices, I'd like there also to be an option to make the div dissapear on clicking the back button. Unfortunately, I can not get it to work in practice at all. I have tried these answers:

  1. handling back button in android from jquery
  2. Take control of hardware back button jquery mobile

But both seem to fail in this task, and the others use plugins, which I'd like to avoid. Tested on LG G2 Mini and Sony Xperia Z1

Community
  • 1
  • 1
aln447
  • 981
  • 2
  • 15
  • 44

1 Answers1

0

One approach would be to use the HTML5 History API.

When opening the popup you can push a state to the history stack before opening the popup: history.pushState({popupOpen: false}, "My title", "index.html"); This method automatically updates the page title (which is currently ignored in most browser implementations) and the last part of the url, that will be displayed in the browser bar. In most cases, you can enter your filename here. The first argument is an object containing the data you can access later when popping a state.

As soon as you have pushed a state to the history stack, when pressing the back key, the browser does not return to the last page as usual, but pops the last state on the stack. This applies for all browsers though, if you want the functionality for mobile browsers only, you have to do a browser check before calling history.pushState.

To correctly handle the back event, you need to subscribe to the popstate-Event. This can be done with the following code:

window.addEventListener("popstate", function(event) {
  var data = event.state;
  if(data.popupOpen === false) {
    popupBg.trigger('click');
  }
});

You register an event listener that fires as soon as the user navigates back. In the event.state variable the data you passed in when pushing the state can be accessed again.

Good luck!

Phocacius
  • 1,127
  • 1
  • 13
  • 23