Tuesday, June 23, 2015

Close modal pop up on back button

One of the common requirement in web development is to show pop up on the page. We may want to show some information, images, map etc. in modal pop up. Bootstrap's modal pop is one of the coolest modal pop with nice UI and easy to integrate on the page. It's very popular in responsive web-design as well. But, it comes with lot of cons as well.

Managing back button is to provide better user experience is pain. Since, Android users often use back button and expect to be on the same page when modal pop up is closed. On back button, modal should be closed and it should not redirect to previous page.

Well, there are couple of ways to manage that:

1. Use onbeforeunload: In 'onbeforeunload' event close the modal pop up. But, this event will always ask user to 'stay on the page' or 'Leave the page' as alert. At times, where we have form on page with modal pop up, we may use this approach. Since, we want to inform user that filled data can be lost. But, in other cases. This does not work.


2. Use onhashchange: The second way is to add a hash in window when the modal pop up is opened and move the history to previous page when modal pop up is closed.


Some people may argue to set the window.location.hash = "modal" when modal is opened and window.location.hash = "" when modal is closed. But, setting hash each time will add pages to history. So, we need to move the page to previous state with window.history.back(); But, above code will handle the case when modal is opened and closed with their respective button. We need to capture back button as well, which can be done by checking hash value with 'onhashchange'

Above approach can also be used to close nav-bar, slide menu etc.