I'm working with Lightbox 2, as it meets nearly every one of my requirements and appears to be the most recently updated, low profile, quality 'Lightbox' jQuery plugin I have come across. The only issue I have with it is that two of the images (close and loading) are hard-coded into the .js file, and there are no examples for passing arguments into the script to override this. I'm not good enough with JS to use the documentation that is the source code.
(function() {
var $, Lightbox, LightboxOptions;
$ = jQuery;
LightboxOptions = (function() {
function LightboxOptions() {
this.fileLoadingImage = 'images/loading.gif';
this.fileCloseImage = 'images/close.png';
this.resizeDuration = 700;
this.fadeDuration = 500;
this.labelImage = "Image";
this.labelOf = "of";
}
return LightboxOptions;
})();
Lightbox = (function() {
function Lightbox(options) {
this.options = options;
this.album = [];
this.currentImageIndex = void 0;
this.init();
}
[...]
})();
$(function() {
var lightbox, options;
options = new LightboxOptions;
return lightbox = new Lightbox(options);
});
}).call(this);
The entire file can be seen on GitHub if I have not included enough of the code. In the included sections, this.fileLoadingImage
and this.fileCloseImage
are given a path relative to the HTML file that executes it. For example, http://mywebsite.com/
. However, my CSS, JS, images, etc. are all served from http://static[number].mywebsitestatic.com/
. Rather than hard-coding a single one of my available static URLs into the .js file, I'd prefer to make this a more re-usable solution so that if this available subdomains or parent domains change I don't have to update this file as well.
The site is a Django app, so in the template code I can simply use {{ STATIC_URL }}
to write out the proper static file URL for a given page and pass that into the .js file. But how? For example, I'd like to be able to do the following (while avoiding global variables):
<script>
/* instantiate a new version of Lightbox */
newLightbox.fileLoadingImage = "{{ STATIC_URL }}img/lightbox/loading.gif";
newLightbox.fileCloseImage = "{{ STATIC_URL }}img/lightbox/close.gif";
</script>
Here is little tweak that allows lightbox.js script to determine its URL; and then the URL of dependency images.
this.fileLoadingImage = 'images/loading.gif';
this.fileCloseImage = 'images/close.png';
this.fileLoadingImage = $('script[src$="/lightbox.js"]')
.attr('src')
.replace(/\/lightbox\.js$/, '/../images/loading.gif');
this.fileCloseImage = $('script[src$="/lightbox.js"]')
.attr('src')
.replace(/\/lightbox\.js$/, '/../images/close.png');
The script works by checking all <script>
tags whose src
attribute ends with /lightbox.js
(hoping that you have only one such script tag). From this point forward, it is easy to calculate the paths of images. Demo Here. Note that demo uses some tricks to work on jsFiddle.