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 the getParameterByName
function in this answer, but of course you can use any strategy you like to pull the query params.
$(document).ready(function() {
var modal = getParameterByName("cb");
if(modal != "") {
$.colorbox({
href: "#" + modal,
inline: true
});
}
});
Then any link to a modal would be:
<a href="yourpage?cb=modal1">Open modal 1</a>
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:
<a href="#colorbox-modal1">Open colorbox</a>
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:
$(document).ready(function() {
$(window).hashchange(function(){
//gets the colorbox content id from the url hash
var getCb = function() { return location.hash.match(/(#colorbox-.*)/) && RegExp.$1 },
cb = getCb();
if(cb) {
$.colorbox({
href: cb,
inline: true,
//if closing with ESC key or overlay click, we
//need to go back so that hashchange is fired
//if the same colorbox is opened again
onClosed: function() {
if(getCb()) {
history.go(-1);
}
}
});
} else {
$.colorbox.close();
}
})
});
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.