Debian Codegraph @

theme/slimbox2/slimbox2.js

raw
1 /*!
2 Slimbox v2.04 - The ultimate lightweight Lightbox clone for jQuery
3 (c) 2007-2010 Christophe Beyls <http://www.digitalia.be>
4 MIT-style license.
5 Modified by Neil Storer <http://www.trips.elusien.co.uk> to add the
6 following feature(s):
7 1) the ability to resize the images in the slide show by using the
8 following two options on the "slimbox" function call:
9 slideHeight,
10 slideWidth.
11 both options can take either:
12 an integer the value of which denotes PIXELS
13 e.g. {slideWidth: 300, slideHeight: 200}
14 or a string specifying the PERCENTAGE size of the slide image
15 e.g. {slideWidth: "50%", slideHeight: "50%"}
16 2) the ability to enable the user to specify a "slideInterval" option
17 that will show a PLAY/PAUSE button that the user can press to enable
18 the slides to be flipped automatically evry "slideInterval" seconds.
19 Modified by Florian Hoech <http://hoech.net> to add the
20 following feature(s):
21 3) the ability to automatically reduce the size of the images in the slide
22 show if they are larger than the given maxima by using the following
23 two options on the "slimbox" function call:
24 maxHeight,
25 maxWidth.
26 both options can take either:
27 an integer the value of which denotes PIXELS
28 e.g. {maxWidth: 600, maxHeight: 400}
29 or a string specifying the PERCENTAGE size of the viewport
30 e.g. {maxWidth: "95%", maxHeight: "95%"}
31 default is 95% of the viewport.
32 4) Bugfix: If html has overflow:hidden and body has overflow:scroll,
33 and the page is scrolled, the image position was not correct in IE < 9
34 5) Automatically skip duplicates in galleries
35 */
36
37 (function($) {
38
39 // DOM elements
40 var overlay, center, image, slide, sizer, prevLink, nextLink, playPauseLink, closeBtn, bottomContainer, bottom, caption, number;
41
42
43 /*
44 Initialization
45 */
46
47 $(function() {
48 // Append the Slimbox HTML code at the bottom of the document
49 $("body").append(
50 $([
51 overlay = $('<div id="lbOverlay" />')[0],
52 center = $('<div id="lbCenter" />')[0],
53 bottomContainer = $('<div id="lbBottomContainer" />')[0]
54 ]).css("display", "none")
55 );
56
57 image = $('<div id="lbImage" />').appendTo(center).append(
58 sizer = $('<div style="position: absolute;" />').append([
59 slide = $('<img id="lbSlide" alt="" />')[0]
60 ])[0]
61 )[0];
62
63 bottom = $('<div id="lbBottom" />').appendTo(bottomContainer).append([
64 closeBtn = $('<a id="lbCloseLink" href="#">Close</a>')[0],
65 caption = $('<div id="lbCaption" />')[0],
66 number = $('<div id="lbNumber" />')[0],
67 prevLink = $('<a id="lbPrevLink" href="#">Prev</a>')[0],
68 nextLink = $('<a id="lbNextLink" href="#">Next</a>')[0],
69 playPauseLink = $('<div id="lbPlayPauseLink" class="lbPlay" />').hide()[0],
70 $('<div style="clear: both;" />')[0]
71 ])[0];
72 });
73
74
75 /*
76 API
77 */
78
79 // Open Slimbox with the specified parameters
80 $.slimbox = function(_images, startImage, _options) {
81
82 // Global variables, accessible to Slimbox only
83 var win = $(window), options, images, activeImage = -1, activeURL, prevImage, nextImage, compatibleOverlay, middle, centerWidth, centerHeight,
84 maxWidth, maxHeight, slideWidth, slideHeight, slideInterval,
85 ie6 = !window.XMLHttpRequest, hiddenElements = [], documentElement = document.documentElement,
86
87 // Preload images
88 preload = {}, preloadPrev = new Image(), preloadNext = new Image();
89
90
91 /*
92 Internal functions
93 */
94
95 function position() {
96 var l = win.scrollLeft(), w = win.width();
97 $([center, bottomContainer]).css("left", l + (w / 2));
98 if (compatibleOverlay) $(overlay).css({left: l, top: win.scrollTop(), width: w, height: win.height()});
99 };
100
101 function setup(open) {
102 if (open) {
103 $("object").add(ie6 ? "select" : "embed").each(function(index, el) {
104 hiddenElements[index] = [el, el.style.visibility];
105 el.style.visibility = "hidden";
106 });
107 } else {
108 $.each(hiddenElements, function(index, el) {
109 el[0].style.visibility = el[1];
110 });
111 hiddenElements = [];
112 }
113 var fn = open ? "bind" : "unbind";
114 win[fn]("scroll resize", position);
115 $(document)[fn]("keydown", keyDown);
116 };
117
118 function keyDown(event) {
119 var code = event.keyCode, fn = $.inArray;
120 // Prevent default keyboard action (like navigating inside the page)
121 return (fn(code, options.closeKeys) >= 0) ? close()
122 : (fn(code, options.nextKeys) >= 0) ? next()
123 : (fn(code, options.previousKeys) >= 0) ? previous()
124 : false;
125 };
126
127 function previous() {
128 return changeImage(prevImage);
129 };
130
131 function next() {
132 if (nextImage < 0) return close();
133 return changeImage(nextImage);
134 };
135
136 function changeImage(imageIndex) {
137 if (imageIndex >= 0) {
138 activeImage = imageIndex;
139 activeURL = images[activeImage][0];
140 prevImage = (activeImage || (options.loop ? images.length : 0)) - 1;
141 nextImage = ((activeImage + 1) % images.length) || (options.loop ? 0 : -1);
142
143 stop();
144 center.className = "lbBeforeLoading";
145 setTimeout(function () {
146 // Only show the loading message if the image takes longer than one fourth of a second to load
147 if (center.className == "lbBeforeLoading") center.className = "lbLoading";
148 }, 250);
149
150 preload = new Image();
151 preload.onload = animateBox;
152 preload.src = activeURL;
153 }
154
155 return false;
156 };
157
158 function animateBox() {
159 center.className = "";
160
161 slideWidth = options.slideWidth || "100%";
162 slideHeight = options.slideHeight || "100%";
163
164 var borderWidth = 10, captionHeight = 42;
165 if (typeof maxWidth == "string" && maxWidth.match(/%$/))
166 maxWidth = win.width() * 0.01 * parseFloat(maxWidth) - borderWidth * 2;
167 if (typeof maxHeight == "string" && maxHeight.match(/%$/))
168 maxHeight = win.height() * 0.01 * parseFloat(maxHeight) - borderWidth * 2 - captionHeight;
169 if (typeof slideWidth == "string" && slideWidth.match(/%$/))
170 slideWidth = preload.width * 0.01 * parseFloat(slideWidth);
171 if (typeof slideHeight == "string" && slideHeight.match(/%$/))
172 slideHeight = preload.height * 0.01 * parseFloat(slideHeight);
173 if (slideWidth > maxWidth || slideHeight > maxHeight) {
174 var factor = Math.min(maxWidth / slideWidth, maxHeight / slideHeight);
175 slideWidth *= factor;
176 slideHeight *= factor;
177 }
178
179 $(slide).attr({src: activeURL});
180 $(image).css({visibility: "hidden", display: ""});
181 $([image, sizer, slide]).width(slideWidth);
182 $([image, sizer, slide]).height(slideHeight);
183
184 $(caption).html(images[activeImage][1] || "");
185 $(number).html((images.length > 1 ? options.counterText : "").replace(/{x}/, activeImage + 1).replace(/{y}/, images.length));
186
187 if (prevImage >= 0) preloadPrev.src = images[prevImage][0];
188 if (nextImage >= 0) preloadNext.src = images[nextImage][0];
189
190 centerWidth = image.offsetWidth;
191 centerHeight = image.offsetHeight;
192 var top = Math.max(0, middle - ((centerHeight + captionHeight) / 2));
193 if (center.offsetHeight != centerHeight) {
194 $(center).animate({height: centerHeight, top: top}, options.resizeDuration, options.resizeEasing);
195 }
196 if (center.offsetWidth != centerWidth) {
197 $(center).animate({width: centerWidth, marginLeft: -centerWidth/2}, options.resizeDuration, options.resizeEasing);
198 }
199 $(center).queue(function() {
200 $(bottomContainer).css({width: centerWidth, top: top + centerHeight, marginLeft: -centerWidth/2, display: ""});
201 $(image).css({display: "none", visibility: "", opacity: ""}).fadeIn(options.imageFadeDuration, animateCaption);
202 });
203 };
204
205 function animateCaption() {
206 if (prevImage >= 0) $(prevLink).fadeIn(200);
207 if (nextImage >= 0) $(nextLink).fadeIn(200);
208 bottomContainer.style.visibility = "";
209 };
210
211 function stop() {
212 preload.onload = null;
213 preload.src = preloadPrev.src = preloadNext.src = activeURL;
214 $([center, image, bottom]).stop(true);
215 $(image).hide();
216 if (prevImage < 0) $(prevLink).fadeOut(200);
217 if (nextImage < 0) $(nextLink).fadeOut(200);
218 };
219
220 function close() {
221 if (activeImage >= 0) {
222 stop();
223 activeImage = prevImage = nextImage = -1;
224 $(center).hide();
225 $(bottomContainer).fadeOut(200);
226 $(overlay).stop().fadeOut(options.overlayFadeDuration, setup);
227 }
228
229 var $playPauseLink = $(playPauseLink);
230 if ($playPauseLink.data('ppHandler') != -1) {
231 clearInterval($playPauseLink.data('ppHandler'));
232 $playPauseLink.data('ppHandler', -1);
233 $playPauseLink.removeClass('lbPause').addClass('lbPlay');
234 }
235
236 return false;
237 };
238
239 $(overlay).unbind('click').click(close);
240 $(image).unbind('click').click(next);
241 $(closeBtn).unbind('click').click(close);
242 $(prevLink).unbind('click').click(previous);
243 $(nextLink).unbind('click').click(next);
244
245 options = $.extend({
246 filterDuplicates: false, // Filter duplicates
247 loop: false, // Allows to navigate between first and last images
248 overlayOpacity: 0.9, // 1 is opaque, 0 is completely transparent (change the color in the CSS file)
249 overlayFadeDuration: 400, // Duration of the overlay fade-in and fade-out animations (in milliseconds)
250 resizeDuration: 400, // Duration of each of the box resize animations (in milliseconds)
251 resizeEasing: "swing", // "swing" is jQuery's default easing
252 initialWidth: 250, // Initial width of the box (in pixels)
253 initialHeight: 250, // Initial height of the box (in pixels)
254 maxWidth: "95%", // Max width of the slide (in pixels or in percent of viewport width as a string e.g. "95%")
255 maxHeight: "95%", // Max height of the slide (in pixels or in percent of viewport height as a string e.g. "95%")
256 slideWidth: "100%", // Initial width of the slide (in pixels or in percent as a string e.g. "50%")
257 slideHeight: "100%", // Initial height of the slide (in pixels or in percent as a string e.g. "50%")
258 slideInterval: 0, // Interval between flipping slides (in seconds), 0 means no automation.
259 imageFadeDuration: 400, // Duration of the image fade-in animation (in milliseconds)
260 captionAnimationDuration: 400, // Duration of the caption animation (in milliseconds)
261 counterText: "{x} / {y}", // Translate or change as you wish, or set it to false to disable counter text for image groups
262 closeKeys: [27, 88, 67], // Array of keycodes to close Slimbox, default: Esc (27), 'x' (88), 'c' (67)
263 previousKeys: [37, 80], // Array of keycodes to navigate to the previous image, default: Left arrow (37), 'p' (80)
264 nextKeys: [39, 78] // Array of keycodes to navigate to the next image, default: Right arrow (39), 'n' (78)
265 }, _options);
266
267 // The function is called for a single image, with URL and Title as first two arguments
268 if (typeof _images == "string") {
269 _images = [[_images, startImage]];
270 startImage = 0;
271 }
272
273 middle = (win.height() / 2);
274 centerWidth = options.initialWidth;
275 centerHeight = options.initialHeight;
276
277 maxWidth = options.maxWidth;
278 maxHeight = options.maxHeight;
279 slideInterval = options.slideInterval;
280
281 $(center).css({top: Math.max(0, middle - (centerHeight / 2)), width: centerWidth, height: centerHeight, marginLeft: -centerWidth/2}).show();
282 compatibleOverlay = ie6 || (overlay.currentStyle && (overlay.currentStyle.position != "fixed"));
283 if (compatibleOverlay) overlay.style.position = "absolute";
284 $(overlay).css("opacity", options.overlayOpacity).fadeIn(options.overlayFadeDuration);
285 position();
286 setup(1);
287
288 images = _images;
289 options.loop = options.loop && (images.length > 1);
290
291 if (slideInterval > 0) {
292 if (typeof($(playPauseLink).data('ppHandler')) == 'undefined'){
293 $(playPauseLink).click(function(){
294 var $this = $(this);
295 if ($this.hasClass('lbPlay')) {
296 if ($this.data('ppHandler') != -1) clearInterval($this.data('ppHandler'));
297 $this.data('ppHandler', setInterval(function(){next();}, slideInterval*1000));
298 $this.removeClass('lbPlay').addClass('lbPause');
299 } else {
300 if ($this.data('ppHandler') != -1) clearInterval($this.data('ppHandler'));
301 $this.data({ppHandler: -1});
302 $this.removeClass('lbPause').addClass('lbPlay');
303 }
304 });
305 }
306 $(playPauseLink).addClass('lbPlay').data({ppHandler: -1}).show();
307 }
308
309 return changeImage(startImage);
310 };
311
312 /*
313 options: Optional options object, see jQuery.slimbox()
314 linkMapper: Optional function taking a link DOM element and an index as arguments and returning an array containing 2 elements:
315 the image URL and the image caption (may contain HTML)
316 linksFilter: Optional function taking a link DOM element and an index as arguments and returning true if the element is part of
317 the image collection that will be shown on click, false if not. "this" refers to the element that was clicked.
318 This function must always return true when the DOM element argument is "this".
319 */
320 $.fn.slimbox = function(_options, linkMapper, linksFilter) {
321 linkMapper = linkMapper || function(el) {
322 return [el.href, el.title];
323 };
324
325 linksFilter = linksFilter || function() {
326 return true;
327 };
328
329 var links = this;
330 options = $.extend({
331 filterDuplicates: false,
332 slideInterval: 0 // Interval between flipping slides (in seconds), 0 means no automation.
333 }, _options);
334
335 slideInterval = options.slideInterval;
336
337 return links.unbind("click").click(function() {
338 // Filter out duplicates
339 var uris = {}, duplicatesFilter = function () {
340 if (!uris[this.href]) uris[this.href] = 0;
341 uris[this.href] ++;
342 return uris[this.href] == 1;
343 }, filteredLinks = options.filterDuplicates ? links.filter(duplicatesFilter) : links;
344
345 // Build the list of images that will be displayed
346 var link = this, startIndex = 0, i = 0, length;
347 filteredLinks = $.grep(filteredLinks, function(el, i) {
348 return linksFilter.call(link, el, i);
349 });
350
351 // We cannot use jQuery.map() because it flattens the returned array
352 for (length = filteredLinks.length; i < length; ++i) {
353 if (filteredLinks[i] == link) startIndex = i;
354 filteredLinks[i] = linkMapper(filteredLinks[i], i);
355 }
356
357 return $.slimbox(filteredLinks, startIndex, _options);
358 });
359 };
360
361 })(jQuery);
362
363 function slimbox_init($, container) {
364 $(container || 'body').find("a[data-lightbox^='lightbox'], a[href$='.gif'], a[href$='.jpg'], a[href$='.jpeg'], a[href$='.png']").filter(function () {
365 return $(this).attr('slimbox') != 'slimbox';
366 }).each(function () {
367 $(this).attr('slimbox', 'slimbox');
368 if (!this.title) {
369 var img = $(this).find('img');
370 if (img.length) {
371 this.title = img.attr('title') || img.attr('alt') || img.attr('src').split('/').pop();
372 img.attr('title', null);
373 }
374 else this.title = $(this).text();
375 }
376 }).slimbox({filterDuplicates: true}, null, function(el) {
377 return this == el || ($(this).data('lightbox').length > 8 && $(this).data('lightbox') == $(el).data('lightbox'));
378 });
379 };
380
381 // AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
382 if (!/ipod|series60|symbian|windows ce/i.test(navigator.userAgent)) {
383 jQuery(function ($) {
384 slimbox_init($);
385 });
386 };