In Colorbox 1.6.0, by default, a click on the displayed photo means the next available photo is displayed.
Can I customize Colorbox to display the previous photo when the user clicks the left half of the current photo?
I know how to determine if mouse click happened in left or right half of div in general, so I considered implementing my own click handler. The click handler would call prev() or next() public methods. Though, I don't know where exactly to put my click handler, as the Colorbox default behaviour takes precedence.
The photos in HTML:
<a class="my-colorbox" href="..." rel="gallery-colorbox" title="First"></a>
<a class="my-colorbox" href="..." rel="gallery-colorbox" title="Second"></a>
<a class="my-colorbox" href="..." rel="gallery-colorbox" title="Third"></a>
Colorbox initialization:
$(".my-colorbox").colorbox({
rel: "gallery-colorbox",
photo: true,
loop: false,
transition: "none",
maxWidth: "90%",
maxHeight: "90%",
...internationalization...
});
Click handler - the idea is taken from this question - Determining if mouse click happened in left or right half of DIV :
$("#cboxLoadedContent").click(function (e) {
var pWidth = $(this).innerWidth();
var pOffset = $(this).offset();
var x = e.pageX - pOffset.left;
if (pWidth / 2 > x)
$.colorbox.prev();
else
$.colorbox.next();
});
The problem is that #cboxLoadedContent
is not the right place to bind the handler as the handler is never called.
I believe this is the code that takes precedence (Colorbox - function load
).
...
photo = settings.get('createImg');
...
if ($related[1] && (settings.get('loop') || $related[index + 1])) {
photo.style.cursor = 'pointer';
photo.onclick = function () {
publicMethod.next();
};
}
Looking at the demo colorbox, I see that when an image is displayed, the topmost dom element (so the one that will get hit in click event) is:
<img class="cboxPhoto" src="somePicture.jpg">
So I would attach the event handler to this particular type of <img>
.
$(".my-colorbox").colorbox({
/* your options */
onComplete: function() {
$(".cboxPhoto").removeAttr("onclick"); //stop the default
}
});
$(document).on("click", ".cboxPhoto", function(e) {
/* your left/right handler code here */
})
By adding the .cboxPhoto
parameter I am filtering the click event that happens on the document and saying I'm only interested when it happens to an element that matches this selector.
This is harder than it needs to be I've logged an issue.
Update:
The issue has been responded to and so if you use v1.6.1 then the onComplete
callback will be:
function() {
$(".cboxPhoto").off("click.cbox");
}