Wednesday, May 5, 2010

Adding custom buttons to jQuery's fancybox


The fancybox is a really cool way of displaying images, divs, etc. I really love its simplicity and coolness. I have started using it in many places now. But I had a problem. I wanted to add buttons next to the close button. Just like Windows has the maximize and minimize buttons next to the close button, I wanted a button that would open in a new window the contents of the fancybox.

I tried to figure out ways to do it without changing the code or the css, but it proved difficult. I would have had to use the onStart function and make changes to the outer div of fancybox dynamically. And also have to add functions for onClick, etc. So I decided that the best way would be to customize the fancybox.

So here is what needs to be done:

Add this to jquery.fancybox-1.3.1.css
#fancybox-customButton1 {
position: absolute;
top: -15px;
right: 15px;
width: 30px;
height: 30px;
background-position: 0px 0px;
cursor: pointer;
z-index: 1103;
display: none;
}


Add all of the following red lines to jquery-fancybox.1.3.1.js

Add var customButton1 on line 19
(function($) {
var tmp, loading, overlay, wrap, outer, inner, close, nav_left, nav_right, customButton1,


Add function on line 173
$('#fancybox-title').appendTo( outer ).hide();
},

fancybox_process_customButton1 = function() {
$('#fancybox-customButton1').css("background-image", "url(" + currentOpts.customButton1Image + ")");
}


Add this to _finish = function () around line 268
if (currentOpts.showCloseButton) {
close.show();
}
if (currentOpts.showCustomButton1) {
customButton1.show();
}

Add this around line 400,
fancybox_process_title();

fancybox_process_customButton1();

Around line 603, add the defaults
selectedOpts.showCloseButton = false;
selectedOpts.showCustomButton1 = false;

Around line 785, add the div
outer.append(
inner = $('
'),

close = $(''),
customButton1 = $(''),

nav_left = $(''),
nav_right = $('')
);

close.click($.fancybox.close);
customButton1.click($.fancybox.onCustomButton1Click);



Around line 995
} else {
wrap.fadeOut( currentOpts.transitionOut == 'none' ? 0 : currentOpts.speedOut, _cleanup);
}
};

$.fancybox.onCustomButton1Click = function() {
currentOpts.onCustomButton1Click();



Around line 1086, add the options that the user can change
showCloseButton : true,
showNavArrows : true,
enableEscapeButton : true,

showCustomButton1 : false,
customButton1Image : null,
customButton1Title : null,
onCustomButton1Click: null,