I’m using the ColorBox jQuery plugin to create modal lightboxes for different purposes around my site. In some cases, we’d like the ajax modal box to create a new history state in the browser so that if I user clicks the Back button, it will close the modal box and bring them back to the underlying view.
Firstly, is behavior like this possible with ColorBox? Second, I’ve looked into window.onhashchange and also this hashchange plugin, but I’m really struggling to put something working together with the ColorBox plugin. I’m hoping someone has attempted or successfully accomplished something similar who may have some insight on how this may be accomplished.
Yeah, that can be done. Here I am assuming you are going to use inline content (hidden) for your modals. Links will open your colorbox modals, but rather than attaching the colorbox to the link in the normal way, you just use normal links with a query parameter defining which modal to open:
?cb=modal1. Then in your docReady you just look for colorbox parameters in the query string and open the appropriate colorbox. This way, it doesn’t matter where your link is, and there’s no need to declare the links as a colorbox link. This example uses thegetParameterByNamefunction in this answer, but of course you can use any strategy you like to pull the query params.Then any link to a modal would be:
Check out the full code for that one at this jsfiddle.
Update: Back button closes colorbox
After reading your comments, I understand better what you want to achieve. So if you only need to close the colorbox when user clicks the back button, instead of query strings you could use url hashes in your links:
In order to watch for changes in the location hash, you could use this jQuery onhashchange plugin, or something similar. And then in your docReady:
Here’s the fiddle for that, but with a disclaimer: IE8 and IE9 have problems with this code while it’s inside a fiddle. Seems ok when I take it out, though.