E
E
Evgeny Zhurov2017-09-01 14:14:36
iPhone
Evgeny Zhurov, 2017-09-01 14:14:36

Is it possible to close a pop-up by clicking on the back button on a smartphone/tablet?

Hello. Actually, the question is in the title)
Is there any handler for the "back" button of mobile devices in js?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
rejjer, 2017-09-10
@rejjer

Theoretically it should help.
1. determine that a smartphone/tablet is currently being used
2. if so: declare some global variable that would be responsible for opening the popup (myPopupOpen) and add this when calling the popup:

history.pushState(null, null, null); // добавляем пустой стейт в историю
window.onpopstate = function(event) {
    if (popupOpen) {
    	closePopUp(); // закрываем попап
    }
    window.onpopstate = null; // удаляем обработчик события перехода по истории
};

But keep in mind that we will now switch to an empty state on the 'forward' button (nothing will change on the page), and states cannot be deleted, so the user may have a misunderstanding.
You can solve it like this:
Use some meaningful anchor history.pushState(null, null, '#myPopup') and make the onpopstate handler global and not delete, and when triggered, look at window.location.hash, if it's empty, hide the popup when it is open (by that myPopupOpen) and open if there is an anchor of the desired popup.
The variable is needed here because we cannot find out what the anchor was on the previous state (document.referrer returns the string before #). It is also important not to spawn the same states side by side, but here everything is already in your hands.
HTML5 History API (habr)
HistoryJS (for those who don't support the HTML5 history API)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question