PJ Brunet PJ Brunet - 5 months ago 19
Javascript Question

I want my tablet's hardware back button (Android) to close my website's lightbox

I have this lightbox (Colorbox) that works perfect, but there's one problem.

If I press the hardware back button on my tablet, I want the lightbox to exit. Instead of closing the lightbox, the hardware back button exits the entire website and goes back in history--that's not what the user would expect.

So I'd like the back button to close my lightbox

$.colorbox.close();
without going back in history. I only want to modify the back button behavior when my lightbox is open.

If it makes any difference, the lightbox closes with the escape key.

Just to be clear, I'm not building an Android application. It's a website with images that open in a jQuery lightbox. If I need "jQuery Mobile" for your solution, please specify.

Here's the link to the lightbox http://www.jacklmoore.com/colorbox/

Thanks to Radek Pech's solution, it's working and I didn't need jQuery Mobile either. You can try out the lightbox here if you're curious http://ProductInterest.com just tap one of the thumbnails.

Answer

When you open the lightbox, you must add new history state.

Then you can watch for popstate event end close the lightbox.

history.pushState(null, "Colorbox", '#colorbox');

window.onpopstate = function(event) {
    $.colorbox.close();
};