Friday, 29 March 2019

JavaScript - close popup with back button

I have a custom popup functionality. What I want is for the browser back button to close this popup.

My ideal scenario would be to NOT show a hashtag in the URL bar.

I have tried putting window.history.pushState('forward', null, ''); in my showPopup() function and then doing the following:

$(window).on('popstate', function () {
    closePopup();
});

This does work but the problem is when I manually close the popup I have to press the back button twice to navigate back to the previous page (obviously because a browser history entry was added when the popup was opened).

What is the best way of doing this? Can it be done without adding a browser history entry? Essentially what I am trying to do is replicate the behaviour of a mobile app. Press the back button in a mobile app will usually dismiss any open modals or context menus.

$('.popup-link').click(function() {
    showPopup();
});

$('.popup-close').click(function() {
    hidePopup();
});

function showPopup() {
    $('.popup').addClass('active');
}

function hidePopup() {
    $('.popup').removeClass('active');
}
.popup {
  background-color: #ccc;
  width: 300px;
  height: 300px;
  display: none;
}

.popup.active {
    display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="popup-link">Click</button>

<div class="popup">
    <button class="popup-close">x</button>
    <!-- popup content here -->
</div>


from JavaScript - close popup with back button

No comments:

Post a Comment