Pretty Photo Set linking Issues - javascript

Yesterday a nice stack overflow user helped me to trigger the Jquery Prettyphoto Lightbox from a DIV element rather than an A element.
You can find that solution here
This works... Almost.
Pretty Photo looks for all the links that reference it and then compiles them into a slideshow of iframes. Normally when you click on a link it will open up the iframe lightbox corresponding to the link i clicked on.
However with this new DIV solution it is opening up to the first iframe link it finds on the page, rather than the link I click on.
This must obviously be happening because I have altered the javascript call code from
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("a[rel^='prettyPhoto[iframes]']").prettyPhoto();
});
</script>
to
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("div[class^='prettyphoto[iframes]']").prettyPhoto();
});
</script>
I have been going through the other JS files but I am not a javascript programmer.
I am going to post the entire JS file. Maybe someone can see what javascript I need to change to make this DIV element work like an A element.
(function($) {
$.prettyPhoto = {version: '2.5.4'};
$.fn.prettyPhoto = function(settings) {
settings = jQuery.extend({
animationSpeed: 'normal', /* fast/slow/normal */
padding: 40, /* padding for each side of the picture */
opacity: 0.80, /* Value between 0 and 1 */
showTitle: true, /* true/false */
allowresize: true, /* true/false */
counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
theme: 'light_rounded', /* light_rounded / dark_rounded / light_square / dark_square */
hideflash: false, /* Hides all the flash object on a page, set to TRUE if flash appears over prettyPhoto */
modal: false, /* If set to true, only the close button will close the window */
changepicturecallback: function(){}, /* Called everytime an item is shown/changed */
callback: function(){} /* Called when prettyPhoto is closed */
}, settings);
// Fallback to a supported theme for IE6
if($.browser.msie && $.browser.version == 6){
settings.theme = "light_square";
}
if($('.pp_overlay').size() == 0) {
_buildOverlay(); // If the overlay is not there, inject it!
}else{
// Set my global selectors
$pp_pic_holder = $('.pp_pic_holder');
$ppt = $('.ppt');
}
// Global variables accessible only by prettyPhoto
var doresize = true, percentBased = false, correctSizes,
// Cached selectors
$pp_pic_holder, $ppt,
// prettyPhoto container specific
pp_contentHeight, pp_contentWidth, pp_containerHeight, pp_containerWidth, pp_type = 'image',
//Gallery specific
setPosition = 0,
// Global elements
$scrollPos = _getScroll();
// Window/Keyboard events
$(window).scroll(function(){ $scrollPos = _getScroll(); _centerOverlay(); _resizeOverlay(); });
$(window).resize(function(){ _centerOverlay(); _resizeOverlay(); });
$(document).keydown(function(e){
if($pp_pic_holder.is(':visible'))
switch(e.keyCode){
case 37:
$.prettyPhoto.changePage('previous');
break;
case 39:
$.prettyPhoto.changePage('next');
break;
case 27:
if(!settings.modal)
$.prettyPhoto.close();
break;
};
});
// Bind the code to each links
$(this).each(function(){
$(this).bind('click',function(){
link = this; // Fix scoping
// Find out if the picture is part of a set
theRel = $(this).attr('rel');
galleryRegExp = /\[(?:.*)\]/;
theGallery = galleryRegExp.exec(theRel);
// Build the gallery array
var images = new Array(), titles = new Array(), descriptions = new Array();
if(theGallery){
$('a[rel*='+theGallery+']').each(function(i){
if($(this)[0] === $(link)[0]) setPosition = i; // Get the position in the set
images.push($(this).attr('href'));
titles.push($(this).find('img').attr('alt'));
descriptions.push($(this).attr('title'));
});
}else{
images = $(this).attr('href');
titles = ($(this).find('img').attr('alt')) ? $(this).find('img').attr('alt') : '';
descriptions = ($(this).attr('title')) ? $(this).attr('title') : '';
}
$.prettyPhoto.open(images,titles,descriptions);
return false;
});
});
/**
* Opens the prettyPhoto modal box.
* #param image {String,Array} Full path to the image to be open, can also be an array containing full images paths.
* #param title {String,Array} The title to be displayed with the picture, can also be an array containing all the titles.
* #param description {String,Array} The description to be displayed with the picture, can also be an array containing all the descriptions.
*/
$.prettyPhoto.open = function(gallery_images,gallery_titles,gallery_descriptions) {
// To fix the bug with IE select boxes
if($.browser.msie && $.browser.version == 6){
$('select').css('visibility','hidden');
};
// Hide the flash
if(settings.hideflash) $('object,embed').css('visibility','hidden');
// Convert everything to an array in the case it's a single item
images = $.makeArray(gallery_images);
titles = $.makeArray(gallery_titles);
descriptions = $.makeArray(gallery_descriptions);
if($('.pp_overlay').size() == 0) {
_buildOverlay(); // If the overlay is not there, inject it!
}else{
// Set my global selectors
$pp_pic_holder = $('.pp_pic_holder');
$ppt = $('.ppt');
}
$pp_pic_holder.attr('class','pp_pic_holder ' + settings.theme); // Set the proper theme
isSet = ($(images).size() > 0) ? true : false; // Find out if it's a set
_getFileType(images[setPosition]); // Set the proper file type
_centerOverlay(); // Center it
// Hide the next/previous links if on first or last images.
_checkPosition($(images).size());
$('.pp_loaderIcon').show(); // Do I need to explain?
// Fade the content in
$('div.pp_overlay').show().fadeTo(settings.animationSpeed,settings.opacity, function(){
$pp_pic_holder.fadeIn(settings.animationSpeed,function(){
// Display the current position
$pp_pic_holder.find('p.currentTextHolder').text((setPosition+1) + settings.counter_separator_label + $(images).size());
// Set the description
if(descriptions[setPosition]){
$pp_pic_holder.find('.pp_description').show().html(unescape(descriptions[setPosition]));
}else{
$pp_pic_holder.find('.pp_description').hide().text('');
};
// Set the title
if(titles[setPosition] && settings.showTitle){
hasTitle = true;
$ppt.html(unescape(titles[setPosition]));
}else{
hasTitle = false;
};
// Inject the proper content
if(pp_type == 'image'){
// Set the new image
imgPreloader = new Image();
// Preload the neighbour images
nextImage = new Image();
if(isSet && setPosition > $(images).size()) nextImage.src = images[setPosition + 1];
prevImage = new Image();
if(isSet && images[setPosition - 1]) prevImage.src = images[setPosition - 1];
pp_typeMarkup = '<img id="fullResImage" src="" />';
$pp_pic_holder.find('#pp_full_res')[0].innerHTML = pp_typeMarkup;
$pp_pic_holder.find('.pp_content').css('overflow','hidden');
$pp_pic_holder.find('#fullResImage').attr('src',images[setPosition]);
imgPreloader.onload = function(){
// Fit item to viewport
correctSizes = _fitToViewport(imgPreloader.width,imgPreloader.height);
_showContent();
};
imgPreloader.src = images[setPosition];
}else{
// Get the dimensions
movie_width = ( parseFloat(grab_param('width',images[setPosition])) ) ? grab_param('width',images[setPosition]) : "425";
movie_height = ( parseFloat(grab_param('height',images[setPosition])) ) ? grab_param('height',images[setPosition]) : "344";
// If the size is % based, calculate according to window dimensions
if(movie_width.indexOf('%') != -1 || movie_height.indexOf('%') != -1){
movie_height = ($(window).height() * parseFloat(movie_height) / 100) - 100;
movie_width = ($(window).width() * parseFloat(movie_width) / 100) - 100;
percentBased = true;
}
movie_height = parseFloat(movie_height);
movie_width = parseFloat(movie_width);
if(pp_type == 'quicktime') movie_height+=15; // Add space for the control bar
// Fit item to viewport
correctSizes = _fitToViewport(movie_width,movie_height);
if(pp_type == 'youtube'){
pp_typeMarkup = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+correctSizes['width']+'" height="'+correctSizes['height']+'"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://www.youtube.com/v/'+grab_param('v',images[setPosition])+'" /><embed src="http://www.youtube.com/v/'+grab_param('v',images[setPosition])+'" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="'+correctSizes['width']+'" height="'+correctSizes['height']+'"></embed></object>';
}else if(pp_type == 'quicktime'){
pp_typeMarkup = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" height="'+correctSizes['height']+'" width="'+correctSizes['width']+'"><param name="src" value="'+images[setPosition]+'"><param name="autoplay" value="true"><param name="type" value="video/quicktime"><embed src="'+images[setPosition]+'" height="'+correctSizes['height']+'" width="'+correctSizes['width']+'" autoplay="true" type="video/quicktime" pluginspage="http://www.apple.com/quicktime/download/"></embed></object>';
}else if(pp_type == 'flash'){
flash_vars = images[setPosition];
flash_vars = flash_vars.substring(images[setPosition].indexOf('flashvars') + 10,images[setPosition].length);
filename = images[setPosition];
filename = filename.substring(0,filename.indexOf('?'));
pp_typeMarkup = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+correctSizes['width']+'" height="'+correctSizes['height']+'"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="'+filename+'?'+flash_vars+'" /><embed src="'+filename+'?'+flash_vars+'" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="'+correctSizes['width']+'" height="'+correctSizes['height']+'"></embed></object>';
}else if(pp_type == 'iframe'){
movie_url = images[setPosition];
movie_url = movie_url.substr(0,movie_url.indexOf('iframe')-1);
pp_typeMarkup = '<iframe src ="'+movie_url+'" width="'+(correctSizes['width']-10)+'" height="'+(correctSizes['height']-10)+'" frameborder="no"></iframe>';
}
// Show content
_showContent();
}
});
});
};
/**
* Change page in the prettyPhoto modal box
* #param direction {String} Direction of the paging, previous or next.
*/
$.prettyPhoto.changePage = function(direction){
if(direction == 'previous') {
setPosition--;
if (setPosition < 0){
setPosition = 0;
return;
}
}else{
if($('.pp_arrow_next').is('.disabled')) return;
setPosition++;
};
// Allow the resizing of the images
if(!doresize) doresize = true;
_hideContent();
$('a.pp_expand,a.pp_contract').fadeOut(settings.animationSpeed,function(){
$(this).removeClass('pp_contract').addClass('pp_expand');
$.prettyPhoto.open(images,titles,descriptions);
});
};
/**
* Closes the prettyPhoto modal box.
*/
$.prettyPhoto.close = function(){
$pp_pic_holder.find('object,embed').css('visibility','hidden');
$('div.pp_pic_holder,div.ppt').fadeOut(settings.animationSpeed);
$('div.pp_overlay').fadeOut(settings.animationSpeed, function(){
$('div.pp_overlay,div.pp_pic_holder,div.ppt').remove();
// To fix the bug with IE select boxes
if($.browser.msie && $.browser.version == 6){
$('select').css('visibility','visible');
};
// Show the flash
if(settings.hideflash) $('object,embed').css('visibility','visible');
setPosition = 0;
settings.callback();
});
doresize = true;
};
/**
* Set the proper sizes on the containers and animate the content in.
*/
_showContent = function(){
$('.pp_loaderIcon').hide();
if($.browser.opera) {
windowHeight = window.innerHeight;
windowWidth = window.innerWidth;
}else{
windowHeight = $(window).height();
windowWidth = $(window).width();
};
// Calculate the opened top position of the pic holder
projectedTop = $scrollPos['scrollTop'] + ((windowHeight/2) - (correctSizes['containerHeight']/2));
if(projectedTop < 0) projectedTop = 0 + $pp_pic_holder.find('.ppt').height();
// Resize the content holder
$pp_pic_holder.find('.pp_content').animate({'height':correctSizes['contentHeight']},settings.animationSpeed);
// Resize picture the holder
$pp_pic_holder.animate({
'top': projectedTop,
'left': ((windowWidth/2) - (correctSizes['containerWidth']/2)),
'width': correctSizes['containerWidth']
},settings.animationSpeed,function(){
$pp_pic_holder.width(correctSizes['containerWidth']);
$pp_pic_holder.find('.pp_hoverContainer,#fullResImage').height(correctSizes['height']).width(correctSizes['width']);
// Fade the new image
$pp_pic_holder.find('#pp_full_res').fadeIn(settings.animationSpeed);
// Show the nav
if(isSet && pp_type=="image") { $pp_pic_holder.find('.pp_hoverContainer').fadeIn(settings.animationSpeed); }else{ $pp_pic_holder.find('.pp_hoverContainer').hide(); }
$pp_pic_holder.find('.pp_details').fadeIn(settings.animationSpeed);
// Show the title
if(settings.showTitle && hasTitle){
$ppt.css({
'top' : $pp_pic_holder.offset().top - 20,
'left' : $pp_pic_holder.offset().left + (settings.padding/2),
'display' : 'none'
});
$ppt.fadeIn(settings.animationSpeed);
};
// Fade the resizing link if the image is resized
if(correctSizes['resized']) $('a.pp_expand,a.pp_contract').fadeIn(settings.animationSpeed);
// Once everything is done, inject the content if it's now a photo
if(pp_type != 'image') $pp_pic_holder.find('#pp_full_res')[0].innerHTML = pp_typeMarkup;
// Callback!
settings.changepicturecallback();
});
};
/**
* Hide the content...DUH!
*/
function _hideContent(){
// Fade out the current picture
$pp_pic_holder.find('#pp_full_res object,#pp_full_res embed').css('visibility','hidden');
$pp_pic_holder.find('.pp_hoverContainer,.pp_details').fadeOut(settings.animationSpeed);
$pp_pic_holder.find('#pp_full_res').fadeOut(settings.animationSpeed,function(){
$('.pp_loaderIcon').show();
});
// Hide the title
$ppt.fadeOut(settings.animationSpeed);
}
/**
* Check the item position in the gallery array, hide or show the navigation links
* #param setCount {integer} The total number of items in the set
*/
function _checkPosition(setCount){
// If at the end, hide the next link
if(setPosition == setCount-1) {
$pp_pic_holder.find('a.pp_next').css('visibility','hidden');
$pp_pic_holder.find('a.pp_arrow_next').addClass('disabled').unbind('click');
}else{
$pp_pic_holder.find('a.pp_next').css('visibility','visible');
$pp_pic_holder.find('a.pp_arrow_next.disabled').removeClass('disabled').bind('click',function(){
$.prettyPhoto.changePage('next');
return false;
});
};
// If at the beginning, hide the previous link
if(setPosition == 0) {
$pp_pic_holder.find('a.pp_previous').css('visibility','hidden');
$pp_pic_holder.find('a.pp_arrow_previous').addClass('disabled').unbind('click');
}else{
$pp_pic_holder.find('a.pp_previous').css('visibility','visible');
$pp_pic_holder.find('a.pp_arrow_previous.disabled').removeClass('disabled').bind('click',function(){
$.prettyPhoto.changePage('previous');
return false;
});
};
// Hide the bottom nav if it's not a set.
if(setCount > 1) {
$('.pp_nav').show();
}else{
$('.pp_nav').hide();
}
};
/**
* Resize the item dimensions if it's bigger than the viewport
* #param width {integer} Width of the item to be opened
* #param height {integer} Height of the item to be opened
* #return An array containin the "fitted" dimensions
*/
function _fitToViewport(width,height){
hasBeenResized = false;
_getDimensions(width,height);
// Define them in case there's no resize needed
imageWidth = width;
imageHeight = height;
windowHeight = $(window).height();
windowWidth = $(window).width();
if( ((pp_containerWidth > windowWidth) || (pp_containerHeight > windowHeight)) && doresize && settings.allowresize && !percentBased) {
hasBeenResized = true;
notFitting = true;
while (notFitting){
if((pp_containerWidth > windowWidth)){
imageWidth = (windowWidth - 200);
imageHeight = (height/width) * imageWidth;
}else if((pp_containerHeight > windowHeight)){
imageHeight = (windowHeight - 200);
imageWidth = (width/height) * imageHeight;
}else{
notFitting = false;
};
pp_containerHeight = imageHeight;
pp_containerWidth = imageWidth;
};
_getDimensions(imageWidth,imageHeight);
};
return {
width:imageWidth,
height:imageHeight,
containerHeight:pp_containerHeight,
containerWidth:pp_containerWidth,
contentHeight:pp_contentHeight,
contentWidth:pp_contentWidth,
resized:hasBeenResized
};
};
/**
* Get the containers dimensions according to the item size
* #param width {integer} Width of the item to be opened
* #param height {integer} Height of the item to be opened
*/
function _getDimensions(width,height){
$pp_pic_holder.find('.pp_details').width(width).find('.pp_description').width(width - parseFloat($pp_pic_holder.find('a.pp_close').css('width'))); /* To have the correct height */
// Get the container size, to resize the holder to the right dimensions
pp_contentHeight = height + $pp_pic_holder.find('.pp_details').height() + parseFloat($pp_pic_holder.find('.pp_details').css('marginTop')) + parseFloat($pp_pic_holder.find('.pp_details').css('marginBottom'));
pp_contentWidth = width;
pp_containerHeight = pp_contentHeight + $pp_pic_holder.find('.ppt').height() + $pp_pic_holder.find('.pp_top').height() + $pp_pic_holder.find('.pp_bottom').height();
pp_containerWidth = width + settings.padding;
}
function _getFileType(itemSrc){
if (itemSrc.match(/youtube\.com\/watch/i)) {
pp_type = 'youtube';
}else if(itemSrc.indexOf('.mov') != -1){
pp_type = 'quicktime';
}else if(itemSrc.indexOf('.swf') != -1){
pp_type = 'flash';
}else if(itemSrc.indexOf('iframe') != -1){
pp_type = 'iframe'
}else{
pp_type = 'image';
};
};
function _centerOverlay(){
if($.browser.opera) {
windowHeight = window.innerHeight;
windowWidth = window.innerWidth;
}else{
windowHeight = $(window).height();
windowWidth = $(window).width();
};
if(doresize) {
$pHeight = $pp_pic_holder.height();
$pWidth = $pp_pic_holder.width();
$tHeight = $ppt.height();
projectedTop = (windowHeight/2) + $scrollPos['scrollTop'] - ($pHeight/2);
if(projectedTop < 0) projectedTop = 0 + $tHeight;
$pp_pic_holder.css({
'top': projectedTop,
'left': (windowWidth/2) + $scrollPos['scrollLeft'] - ($pWidth/2)
});
$ppt.css({
'top' : projectedTop - $tHeight,
'left' : (windowWidth/2) + $scrollPos['scrollLeft'] - ($pWidth/2) + (settings.padding/2)
});
};
};
function _getScroll(){
if (self.pageYOffset) {
scrollTop = self.pageYOffset;
scrollLeft = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
scrollTop = document.documentElement.scrollTop;
scrollLeft = document.documentElement.scrollLeft;
} else if (document.body) {// all other Explorers
scrollTop = document.body.scrollTop;
scrollLeft = document.body.scrollLeft;
}
return {scrollTop:scrollTop,scrollLeft:scrollLeft};
};
function _resizeOverlay() {
$('div.pp_overlay').css({
'height':$(document).height(),
'width':$(window).width()
});
};
function _buildOverlay(){
toInject = "";
// Build the background overlay div
toInject += "<div class='pp_overlay'></div>";
// Basic HTML for the picture holder
toInject += '<div class="pp_pic_holder"><div class="pp_top"><div class="pp_left"></div><div class="pp_middle"></div><div class="pp_right"></div></div><div class="pp_content">Expand<div class="pp_loaderIcon"></div><div class="pp_hoverContainer"><a class="pp_next" href="#">next</a><a class="pp_previous" href="#">previous</a></div><div id="pp_full_res"></div><div class="pp_details clearfix"><a class="pp_close" href="#">Close</a><p class="pp_description"></p><div class="pp_nav">Previous<p class="currentTextHolder">0'+settings.counter_separator_label+'0</p>Next</div></div></div><div class="pp_bottom"><div class="pp_left"></div><div class="pp_middle"></div><div class="pp_right"></div></div></div>';
// Basic html for the title holder
toInject += '<div class="ppt"></div>';
$('body').append(toInject);
// So it fades nicely
$('div.pp_overlay').css('opacity',0);
// Set my global selectors
$pp_pic_holder = $('.pp_pic_holder');
$ppt = $('.ppt');
$('div.pp_overlay').css('height',$(document).height()).hide().bind('click',function(){
if(!settings.modal)
$.prettyPhoto.close();
});
$('a.pp_close').bind('click',function(){ $.prettyPhoto.close(); return false; });
$('a.pp_expand').bind('click',function(){
$this = $(this); // Fix scoping
// Expand the image
if($this.hasClass('pp_expand')){
$this.removeClass('pp_expand').addClass('pp_contract');
doresize = false;
}else{
$this.removeClass('pp_contract').addClass('pp_expand');
doresize = true;
};
_hideContent();
$pp_pic_holder.find('.pp_hoverContainer, .pp_details').fadeOut(settings.animationSpeed);
$pp_pic_holder.find('#pp_full_res').fadeOut(settings.animationSpeed,function(){
$.prettyPhoto.open(images,titles,descriptions);
});
return false;
});
$pp_pic_holder.find('.pp_previous, .pp_arrow_previous').bind('click',function(){
$.prettyPhoto.changePage('previous');
return false;
});
$pp_pic_holder.find('.pp_next, .pp_arrow_next').bind('click',function(){
$.prettyPhoto.changePage('next');
return false;
});
$pp_pic_holder.find('.pp_hoverContainer').css({
'margin-left': settings.padding/2
});
};
};
function grab_param(name,url){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return results[1];
}
})(jQuery);
Here is the link to the lighbox.
All help is appreciated.
Thanks,
Tim

It looks like the pretty photos code is using the rel attribute explicitly, do your div's have rel? You are calling the code on $("div[class^='menuitem[iframes]']").prettyPhoto();
But then pretty photos is looking for theRel = $(this).attr('rel'); and running against that.

Related

Trying to add ALT tag within popup lightbox Lightbox2 for ADA Compliance Standards

I am updating a client's site to include alt tags to bring their site to ADA compliance. I have a few pages that use Lightbox2 from https://lokeshdhakar.com/projects/lightbox2. I added the ALT attribute to my array, but it's not being called in the script, so didn't get added.
<img src="images/slide-show/at-the-beach-boys-th.jpg" alt="Small boys use sand toys on Long Sands Beach." width="256" height="176" />
I have tried to edit the lightbox.js to include the alt tag call, but have not been successful.
Contents of lightbox.js
// -----------------------------------------------------------------------------------
//
// Lightbox v2.03.3
// by Lokesh Dhakar - http://www.huddletogether.com
// 5/21/06
//
// For more information on this script, visit:
// http://huddletogether.com/projects/lightbox2/
//
// Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//
// Credit also due to those who have helped, inspired, and made their code available to the public.
// Including: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.com), Thomas Fuchs(mir.aculo.us), and others.
//
//
// -----------------------------------------------------------------------------------
/*
Table of Contents
-----------------
Configuration
Global Variables
Extending Built-in Objects
- Object.extend(Element)
- Array.prototype.removeDuplicates()
- Array.prototype.empty()
Lightbox Class Declaration
- initialize()
- updateImageList()
- start()
- changeImage()
- resizeImageContainer()
- showImage()
- updateDetails()
- updateNav()
- enableKeyboardNav()
- disableKeyboardNav()
- keyboardAction()
- preloadNeighborImages()
- end()
Miscellaneous Functions
- getPageScroll()
- getPageSize()
- getKey()
- listenKey()
- showSelectBoxes()
- hideSelectBoxes()
- showFlash()
- hideFlash()
- pause()
- initLightbox()
Function Calls
- addLoadEvent(initLightbox)
*/
// -----------------------------------------------------------------------------------
//
// Configuration
//
var fileLoadingImage = "../lightbox_assets/images/loading.gif";
var fileBottomNavCloseImage = "../lightbox_assets/images/closelabel.gif";
var overlayOpacity = 0.8; // controls transparency of shadow overlay
var animate = true; // toggles resizing animations
var resizeSpeed = 7; // controls the speed of the image resizing animations (1=slowest and 10=fastest)
var borderSize = 10; //if you adjust the padding in the CSS, you will need to update this variable
// -----------------------------------------------------------------------------------
//
// Global Variables
//
var imageArray = new Array;
var activeImage;
if(animate == true){
overlayDuration = 0.2; // shadow fade in/out duration
if(resizeSpeed > 10){ resizeSpeed = 10;}
if(resizeSpeed < 1){ resizeSpeed = 1;}
resizeDuration = (11 - resizeSpeed) * 0.15;
} else {
overlayDuration = 0;
resizeDuration = 0;
}
// -----------------------------------------------------------------------------------
//
// Additional methods for Element added by SU, Couloir
// - further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
getWidth: function(element) {
element = $(element);
return element.offsetWidth;
},
setWidth: function(element,w) {
element = $(element);
element.style.width = w +"px";
},
setHeight: function(element,h) {
element = $(element);
element.style.height = h +"px";
},
setTop: function(element,t) {
element = $(element);
element.style.top = t +"px";
},
setLeft: function(element,l) {
element = $(element);
element.style.left = l +"px";
},
setSrc: function(element,src) {
element = $(element);
element.src = src;
},
setHref: function(element,href) {
element = $(element);
element.href = href;
},
setInnerHTML: function(element,content) {
element = $(element);
element.innerHTML = content;
}
});
// -----------------------------------------------------------------------------------
//
// Extending built-in Array object
// - array.removeDuplicates()
// - array.empty()
//
Array.prototype.removeDuplicates = function () {
for(i = 0; i < this.length; i++){
for(j = this.length-1; j>i; j--){
if(this[i][0] == this[j][0]){
this.splice(j,1);
}
}
}
}
// -----------------------------------------------------------------------------------
Array.prototype.empty = function () {
for(i = 0; i <= this.length; i++){
this.shift();
}
}
// -----------------------------------------------------------------------------------
//
// Lightbox Class Declaration
// - initialize()
// - start()
// - changeImage()
// - resizeImageContainer()
// - showImage()
// - updateDetails()
// - updateNav()
// - enableKeyboardNav()
// - disableKeyboardNav()
// - keyboardNavAction()
// - preloadNeighborImages()
// - end()
//
// Structuring of code inspired by Scott Upton (http://www.uptonic.com/)
//
var Lightbox = Class.create();
Lightbox.prototype = {
// initialize()
// Constructor runs on completion of the DOM loading. Calls updateImageList and then
// the function inserts html at the bottom of the page which is used to display the shadow
// overlay and the image container.
//
initialize: function() {
this.updateImageList();
// Code inserts html at the bottom of the page that looks similar to this:
//
// <div id="overlay"></div>
// <div id="lightbox">
// <div id="outerImageContainer">
// <div id="imageContainer">
// <img id="lightboxImage" alt="container for enlarged images">
// <div style="" id="hoverNav">
//
//
// </div>
// <div id="loading">
// <a href="#" id="loadingLink">
// <img src="images/loading.gif" alt"Waiting to load">
// </a>
// </div>
// </div>
// </div>
// <div id="imageDataContainer">
// <div id="imageData">
// <div id="imageDetails">
// <span id="caption"></span>
// <span id="numberDisplay"></span>
// </div>
// <div id="bottomNav">
// <a href="#" id="bottomNavClose">
// <img src="../images/close.gif" alt="X graphic to close lightbox">
// </a>
// </div>
// </div>
// </div>
// </div>
var objBody = document.getElementsByTagName("body").item(0);
var objOverlay = document.createElement("div");
objOverlay.setAttribute('id','overlay');
objOverlay.style.display = 'none';
objOverlay.onclick = function() { myLightbox.end(); }
objBody.appendChild(objOverlay);
var objLightbox = document.createElement("div");
objLightbox.setAttribute('id','lightbox');
objLightbox.style.display = 'none';
objLightbox.onclick = function(e) { // close Lightbox is user clicks shadow overlay
if (!e) var e = window.event;
var clickObj = Event.element(e).id;
if ( clickObj == 'lightbox') {
myLightbox.end();
}
};
objBody.appendChild(objLightbox);
var objOuterImageContainer = document.createElement("div");
objOuterImageContainer.setAttribute('id','outerImageContainer');
objLightbox.appendChild(objOuterImageContainer);
// When Lightbox starts it will resize itself from 250 by 250 to the current image dimension.
// If animations are turned off, it will be hidden as to prevent a flicker of a
// white 250 by 250 box.
if(animate){
Element.setWidth('outerImageContainer', 250);
Element.setHeight('outerImageContainer', 250);
} else {
Element.setWidth('outerImageContainer', 1);
Element.setHeight('outerImageContainer', 1);
}
var objImageContainer = document.createElement("div");
objImageContainer.setAttribute('id','imageContainer');
objOuterImageContainer.appendChild(objImageContainer);
var objLightboxImage = document.createElement("img");
objLightboxImage.setAttribute('id','lightboxImage');
objImageContainer.appendChild(objLightboxImage);
var objHoverNav = document.createElement("div");
objHoverNav.setAttribute('id','hoverNav');
objImageContainer.appendChild(objHoverNav);
var objPrevLink = document.createElement("a");
objPrevLink.setAttribute('id','prevLink');
objPrevLink.setAttribute('href','#');
objHoverNav.appendChild(objPrevLink);
var objNextLink = document.createElement("a");
objNextLink.setAttribute('id','nextLink');
objNextLink.setAttribute('href','#');
objHoverNav.appendChild(objNextLink);
var objLoading = document.createElement("div");
objLoading.setAttribute('id','loading');
objImageContainer.appendChild(objLoading);
var objLoadingLink = document.createElement("a");
objLoadingLink.setAttribute('id','loadingLink');
objLoadingLink.setAttribute('href','#');
objLoadingLink.onclick = function() { myLightbox.end(); return false; }
objLoading.appendChild(objLoadingLink);
var objLoadingImage = document.createElement("img");
objLoadingImage.setAttribute('src', fileLoadingImage);
objLoadingImage.setAttribute('alt', 'Image Loading icon');
objLoadingLink.appendChild(objLoadingImage);
var objImageDataContainer = document.createElement("div");
objImageDataContainer.setAttribute('id','imageDataContainer');
objLightbox.appendChild(objImageDataContainer);
var objImageData = document.createElement("div");
objImageData.setAttribute('id','imageData');
objImageDataContainer.appendChild(objImageData);
var objImageDetails = document.createElement("div");
objImageDetails.setAttribute('id','imageDetails');
objImageData.appendChild(objImageDetails);
var objCaption = document.createElement("span");
objCaption.setAttribute('id','caption');
objImageDetails.appendChild(objCaption);
var objNumberDisplay = document.createElement("span");
objNumberDisplay.setAttribute('id','numberDisplay');
objImageDetails.appendChild(objNumberDisplay);
var objBottomNav = document.createElement("div");
objBottomNav.setAttribute('id','bottomNav');
objImageData.appendChild(objBottomNav);
var objBottomNavCloseLink = document.createElement("a");
objBottomNavCloseLink.setAttribute('id','bottomNavClose');
objBottomNavCloseLink.setAttribute('href','#');
objBottomNavCloseLink.onclick = function() { myLightbox.end(); return false; }
objBottomNav.appendChild(objBottomNavCloseLink);
var objBottomNavCloseImage = document.createElement("img");
objBottomNavCloseImage.setAttribute('src', fileBottomNavCloseImage);
objBottomNavCloseImage.setAttribute('alt', 'CLOSE X');
objBottomNavCloseLink.appendChild(objBottomNavCloseImage);
},
//
// updateImageList()
// Loops through anchor tags looking for 'lightbox' references and applies onclick
// events to appropriate links. You can rerun after dynamically adding images w/ajax.
//
updateImageList: function() {
if (!document.getElementsByTagName){ return; }
var anchors = document.getElementsByTagName('a');
var areas = document.getElementsByTagName('area');
// loop through all anchor tags
for (var i=0; i<anchors.length; i++){
var anchor = anchors[i];
var relAttribute = String(anchor.getAttribute('rel'));
// use the string.match() method to catch 'lightbox' references in the rel attribute
if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){
anchor.onclick = function () {myLightbox.start(this); return false;}
}
}
// loop through all area tags
// todo: combine anchor & area tag loops
for (var i=0; i< areas.length; i++){
var area = areas[i];
var relAttribute = String(area.getAttribute('rel'));
// use the string.match() method to catch 'lightbox' references in the rel attribute
if (area.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){
area.onclick = function () {myLightbox.start(this); return false;}
}
}
},
//
// start()
// Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
//
start: function(imageLink) {
hideSelectBoxes();
hideFlash();
// stretch overlay to fill page and fade in
var arrayPageSize = getPageSize();
Element.setWidth('overlay', arrayPageSize[0]);
Element.setHeight('overlay', arrayPageSize[1]);
new Effect.Appear('overlay', { duration: overlayDuration, from: 0.0, to: overlayOpacity });
imageArray = [];
imageNum = 0;
if (!document.getElementsByTagName){ return; }
var anchors = document.getElementsByTagName( imageLink.tagName);
// if image is NOT part of a set..
if((imageLink.getAttribute('rel') == 'lightbox')){
// add single image to imageArray
imageArray.push(new Array(imageLink.getAttribute('href'), imageLink.getAttribute('title')));
} else {
// if image is part of a set..
// loop through anchors, find other images in set, and add them to imageArray
for (var i=0; i<anchors.length; i++){
var anchor = anchors[i];
if (anchor.getAttribute('href') && (anchor.getAttribute('rel') == imageLink.getAttribute('rel'))){
imageArray.push(new Array(anchor.getAttribute('href'), anchor.getAttribute('title')));
}
}
imageArray.removeDuplicates();
while(imageArray[imageNum][0] != imageLink.getAttribute('href')) { imageNum++;}
}
// calculate top and left offset for the lightbox
var arrayPageScroll = getPageScroll();
var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 10);
var lightboxLeft = arrayPageScroll[0];
Element.setTop('lightbox', lightboxTop);
Element.setLeft('lightbox', lightboxLeft);
Element.show('lightbox');
this.changeImage(imageNum);
},
//
// changeImage()
// Hide most elements and preload image in preparation for resizing image container.
//
changeImage: function(imageNum) {
activeImage = imageNum; // update global var
// hide elements during transition
if(animate){ Element.show('loading');}
Element.hide('lightboxImage');
Element.hide('alt');
Element.hide('hoverNav');
Element.hide('prevLink');
Element.hide('nextLink');
Element.hide('imageDataContainer');
Element.hide('numberDisplay');
imgPreloader = new Image();
// once image is preloaded, resize image container
imgPreloader.onload=function(){
Element.setSrc('lightboxImage', imageArray[activeImage][0]);
myLightbox.resizeImageContainer(imgPreloader.width, imgPreloader.height);
imgPreloader.onload=function(){}; // clear onLoad, IE behaves irratically with animated gifs otherwise
}
imgPreloader.src = imageArray[activeImage][0];
},
//
// resizeImageContainer()
//
resizeImageContainer: function( imgWidth, imgHeight) {
// get curren width and height
this.widthCurrent = Element.getWidth('outerImageContainer');
this.heightCurrent = Element.getHeight('outerImageContainer');
// get new width and height
var widthNew = (imgWidth + (borderSize * 2));
var heightNew = (imgHeight + (borderSize * 2));
// scalars based on change from old to new
this.xScale = ( widthNew / this.widthCurrent) * 100;
this.yScale = ( heightNew / this.heightCurrent) * 100;
// calculate size difference between new and old image, and resize if necessary
wDiff = this.widthCurrent - widthNew;
hDiff = this.heightCurrent - heightNew;
if(!( hDiff == 0)){ new Effect.Scale('outerImageContainer', this.yScale, {scaleX: false, duration: resizeDuration, queue: 'front'}); }
if(!( wDiff == 0)){ new Effect.Scale('outerImageContainer', this.xScale, {scaleY: false, delay: resizeDuration, duration: resizeDuration}); }
// if new and old image are same size and no scaling transition is necessary,
// do a quick pause to prevent image flicker.
if((hDiff == 0) && (wDiff == 0)){
if (navigator.appVersion.indexOf("MSIE")!=-1){ pause(250); } else { pause(100);}
}
Element.setHeight('prevLink', imgHeight);
Element.setHeight('nextLink', imgHeight);
Element.setWidth( 'imageDataContainer', widthNew);
this.showImage();
},
//
// showImage()
// Display image and begin preloading neighbors.
//
showImage: function(){
Element.hide('loading');
new Effect.Appear('lightboxImage', { duration: resizeDuration, queue: 'end', afterFinish: function(){ myLightbox.updateDetails(); } });
this.preloadNeighborImages();
},
//
// updateDetails()
// Display caption, image number, and bottom nav.
//
updateDetails: function() {
// if caption is not null
if(imageArray[activeImage][1]){
Element.show('caption');
Element.setInnerHTML( 'caption', imageArray[activeImage][1]);
}
// if image is part of set display 'Image x of x'
if(imageArray.length > 1){
Element.show('numberDisplay');
Element.setInnerHTML( 'numberDisplay', "Image " + eval(activeImage + 1) + " of " + imageArray.length);
}
new Effect.Parallel(
[ new Effect.SlideDown( 'imageDataContainer', { sync: true, duration: resizeDuration, from: 0.0, to: 1.0 }),
new Effect.Appear('imageDataContainer', { sync: true, duration: resizeDuration }) ],
{ duration: resizeDuration, afterFinish: function() {
// update overlay size and update nav
var arrayPageSize = getPageSize();
Element.setHeight('overlay', arrayPageSize[1]);
myLightbox.updateNav();
}
}
);
},
//
// updateNav()
// Display appropriate previous and next hover navigation.
//
updateNav: function() {
Element.show('hoverNav');
// if not first image in set, display prev image button
if(activeImage != 0){
Element.show('prevLink');
document.getElementById('prevLink').onclick = function() {
myLightbox.changeImage(activeImage - 1); return false;
}
}
// if not last image in set, display next image button
if(activeImage != (imageArray.length - 1)){
Element.show('nextLink');
document.getElementById('nextLink').onclick = function() {
myLightbox.changeImage(activeImage + 1); return false;
}
}
this.enableKeyboardNav();
},
//
// enableKeyboardNav()
//
enableKeyboardNav: function() {
document.onkeydown = this.keyboardAction;
},
//
// disableKeyboardNav()
//
disableKeyboardNav: function() {
document.onkeydown = '';
},
//
// keyboardAction()
//
keyboardAction: function(e) {
if (e == null) { // ie
keycode = event.keyCode;
escapeKey = 27;
} else { // mozilla
keycode = e.keyCode;
escapeKey = e.DOM_VK_ESCAPE;
}
key = String.fromCharCode(keycode).toLowerCase();
if((key == 'x') || (key == 'o') || (key == 'c') || (keycode == escapeKey)){ // close lightbox
myLightbox.end();
} else if((key == 'p') || (keycode == 37)){ // display previous image
if(activeImage != 0){
myLightbox.disableKeyboardNav();
myLightbox.changeImage(activeImage - 1);
}
} else if((key == 'n') || (keycode == 39)){ // display next image
if(activeImage != (imageArray.length - 1)){
myLightbox.disableKeyboardNav();
myLightbox.changeImage(activeImage + 1);
}
}
},
//
// preloadNeighborImages()
// Preload previous and next images.
//
preloadNeighborImages: function(){
if((imageArray.length - 1) > activeImage){
preloadNextImage = new Image();
preloadNextImage.src = imageArray[activeImage + 1][0];
}
if(activeImage > 0){
preloadPrevImage = new Image();
preloadPrevImage.src = imageArray[activeImage - 1][0];
}
},
//
// end()
//
end: function() {
this.disableKeyboardNav();
Element.hide('lightbox');
new Effect.Fade('overlay', { duration: overlayDuration});
showSelectBoxes();
showFlash();
}
}
// -----------------------------------------------------------------------------------
//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.com
//
function getPageScroll(){
var xScroll, yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
xScroll = self.pageXOffset;
} else if (document.documentElement && document.documentElement.scrollTop){ // Explorer 6 Strict
yScroll = document.documentElement.scrollTop;
xScroll = document.documentElement.scrollLeft;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
xScroll = document.body.scrollLeft;
}
arrayPageScroll = new Array(xScroll,yScroll)
return arrayPageScroll;
}
// -----------------------------------------------------------------------------------
//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.com
// Edit for Firefox by pHaez
//
function getPageSize(){
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY) {
xScroll = window.innerWidth + window.scrollMaxX;
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
// console.log(self.innerWidth);
// console.log(document.documentElement.clientWidth);
if (self.innerHeight) { // all except Explorer
if(document.documentElement.clientWidth){
windowWidth = document.documentElement.clientWidth;
} else {
windowWidth = self.innerWidth;
}
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) { // other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
// for small pages with total height less then height of the viewport
if(yScroll < windowHeight){
pageHeight = windowHeight;
} else {
pageHeight = yScroll;
}
// console.log("xScroll " + xScroll)
// console.log("windowWidth " + windowWidth)
// for small pages with total width less then width of the viewport
if(xScroll < windowWidth){
pageWidth = xScroll;
} else {
pageWidth = windowWidth;
}
// console.log("pageWidth " + pageWidth)
arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
return arrayPageSize;
}
// -----------------------------------------------------------------------------------
//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//
function getKey(e){
if (e == null) { // ie
keycode = event.keyCode;
} else { // mozilla
keycode = e.which;
}
key = String.fromCharCode(keycode).toLowerCase();
if(key == 'x'){
}
}
// -----------------------------------------------------------------------------------
//
// listenKey()
//
function listenKey () { document.onkeypress = getKey; }
// ---------------------------------------------------
function showSelectBoxes(){
var selects = document.getElementsByTagName("select");
for (i = 0; i != selects.length; i++) {
selects[i].style.visibility = "visible";
}
}
// ---------------------------------------------------
function hideSelectBoxes(){
var selects = document.getElementsByTagName("select");
for (i = 0; i != selects.length; i++) {
selects[i].style.visibility = "hidden";
}
}
// ---------------------------------------------------
function showFlash(){
var flashObjects = document.getElementsByTagName("object");
for (i = 0; i < flashObjects.length; i++) {
flashObjects[i].style.visibility = "visible";
}
var flashEmbeds = document.getElementsByTagName("embed");
for (i = 0; i < flashEmbeds.length; i++) {
flashEmbeds[i].style.visibility = "visible";
}
}
// ---------------------------------------------------
function hideFlash(){
var flashObjects = document.getElementsByTagName("object");
for (i = 0; i < flashObjects.length; i++) {
flashObjects[i].style.visibility = "hidden";
}
var flashEmbeds = document.getElementsByTagName("embed");
for (i = 0; i < flashEmbeds.length; i++) {
flashEmbeds[i].style.visibility = "hidden";
}
}
// ---------------------------------------------------
//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Help from Ran Bar-On [ran2103#gmail.com]
//
function pause(ms){
var date = new Date();
curDate = null;
do{var curDate = new Date();}
while( curDate - date < ms);
}
/*
function pause(numberMillis) {
var curently = new Date().getTime() + sender;
while (new Date().getTime();
}
*/
// ---------------------------------------------------
function initLightbox() { myLightbox = new Lightbox(); }
//Event.observe(window, 'load', initLightbox, false);
I've continued to work on this and have a temporary solution until the mainframe of Lightbox2 has a working alt tag on the overlay (tried up to current version 11.1 but they weren't working). I added a setAlt section after line 122
setAlt: function(element,alt) {
element = $(element);
element.alt = alt;
},
and then added the alt call in the image preloader section (around line 440). I tried calling a value for the ALT in this code, but best I could get was 'undefined', so I've set a static value.
imgPreloader = new Image();
// once image is preloaded, resize image container
imgPreloader.onload=function(){
Element.setSrc('lightboxImage', imageArray[activeImage][0]);
Element.setAlt('lightboxImage', 'Caption below');
// Element.setAlt ('lightboxImage', imageArray[activeImage][0].alt);
//which returned alt="undefined". Couldn't figure out setting VAR
myLightbox.resizeImageContainer(imgPreloader.width, imgPreloader.height);

Auto Scaling Image Annotation

Scalize is a jQuery plugin used for adding custom markers (hotspots) with custom popovers and animations to containers or images.
But now When I click one by one on pointer it show all one by one But I am trying to show only one so when click another pointer will close the other which already opened.
Here is my EXAMPLE
(function(jQuery) {
"use strict";
//----------------------------------------//
// Variable
//----------------------------------------//
var variable = {
width : 0,
height : 0,
selector : '.item-point',
styleSelector : 'circle',
animationSelector : 'pulse2',
animationPopoverIn : 'flipInY',
animationPopoverOut : 'flipOutY',
onInit : null,
getSelectorElement : null,
getValueRemove : null
}
//----------------------------------------//
// Scaling
//----------------------------------------//
var scaling = {
settings : null,
//----------------------------------------//
// Initialize
//----------------------------------------//
init: function(el, options){
this.settings = jQuery.extend(variable, options);
this.event(el);
scaling.layout(el);
jQuery(window).on('load', function(){
scaling.layout(el);
});
jQuery(el).find('.target').on('load', function(){
scaling.layout(el);
});
jQuery(window).on('resize', function(){
scaling.layout(el);
});
},
//----------------------------------------//
// Event
//----------------------------------------//
event : function(elem){
// Set Style Selector
if ( this.settings.styleSelector ) {
jQuery(this.settings.selector).addClass( this.settings.styleSelector );
}
// Set Animation
if ( this.settings.animationSelector ) {
if( this.settings.animationSelector == 'marker' ){
jQuery(this.settings.selector).addClass( this.settings.animationSelector );
jQuery(this.settings.selector).append('<div class="pin"></div>')
jQuery(this.settings.selector).append('<div class="pulse"></div>')
}else{
jQuery(this.settings.selector).addClass( this.settings.animationSelector );
}
}
// Event On Initialize
if ( jQuery.isFunction( this.settings.onInit ) ) {
this.settings.onInit();
}
// Content add class animated element
jQuery(elem).find('.content').addClass('animated');
// Wrapper selector
jQuery(this.settings.selector).wrapAll( "<div class='wrap-selector' />");
// Event Selector
jQuery(this.settings.selector).each(function(){
// Toggle
jQuery('.toggle', this).on('click', function(e){
e.preventDefault();
jQuery(this).closest(scaling.settings.selector).toggleClass('active');
// Selector Click
var content = jQuery(this).closest(scaling.settings.selector).data('popover'),
id = jQuery(content);
if(jQuery(this).closest(scaling.settings.selector).hasClass('active') && !jQuery(this).closest(scaling.settings.selector).hasClass('disabled')){
if ( jQuery.isFunction( scaling.settings.getSelectorElement ) ) {
scaling.settings.getSelectorElement(jQuery(this).closest(scaling.settings.selector));
}
id.fadeIn(500,function(){
if( getBrowserName() == "Safari" ){
setTimeout(function(){
id.removeClass('flipInY');
},125);
}
});
scaling.layout(elem);
id.removeClass(scaling.settings.animationPopoverOut);
id.addClass(scaling.settings.animationPopoverIn);
}else{
if(jQuery.isFunction( scaling.settings.getValueRemove )){
scaling.settings.getValueRemove(jQuery(this).closest(scaling.settings.selector));
}
id.removeClass(scaling.settings.animationPopoverIn);
id.addClass(scaling.settings.animationPopoverOut);
id.delay(500).fadeOut();
}
});
// Exit
var target = jQuery(this).data('popover'),
idTarget = jQuery(target);
idTarget.find('.exit').on('click', function(e){
e.preventDefault();
// selector.removeClass('active');
jQuery('[data-popover="'+ target +'"]').removeClass('active');
idTarget.removeClass(scaling.settings.animationPopoverIn);
idTarget.addClass(scaling.settings.animationPopoverOut);
idTarget.delay(500).fadeOut();
});
});
},
//----------------------------------------//
// Layout
//----------------------------------------//
layout : function(elem){
// Get Original Image
var image = new Image();
image.src = elem.find('.target').attr("src");
// Variable
var width = image.naturalWidth,
height = image.naturalHeight,
getWidthLess = jQuery(elem).width(),
setPersenWidth = getWidthLess/width * 100,
setHeight = height * setPersenWidth / 100;
// Set Heigh Element
jQuery(elem).css("height", setHeight);
// Resize Width
if( jQuery(window).width() < width ){
jQuery(elem).stop().css("width","100%");
}else{
jQuery(elem).stop().css("width",width);
}
// Set Position Selector
jQuery(this.settings.selector).each(function(){
if( jQuery(window).width() < width ){
var getTop = jQuery(this).data("top") * setPersenWidth / 100,
getLeft = jQuery(this).data("left") * setPersenWidth / 100;
}else{
var getTop = jQuery(this).data("top"),
getLeft = jQuery(this).data("left");
}
jQuery(this).css("top", getTop + "px");
jQuery(this).css("left", getLeft + "px");
// Target Position
var target = jQuery(this).data('popover'),
allSize = jQuery(target).find('.head').outerHeight() + jQuery(target).find('.body').outerHeight() + jQuery(target).find('.footer').outerHeight();
jQuery(target).css("left", getLeft + "px");
jQuery(target).css("height", allSize + "px");
if(jQuery(target).hasClass('bottom')){
var getHeight = jQuery(target).outerHeight(),
getTopBottom = getTop - getHeight;
jQuery(target).css("top", getTopBottom + "px");
}else if(jQuery(target).hasClass('center')){
var getHeight = jQuery(target).outerHeight() * 0.50,
getTopBottom = getTop - getHeight;
jQuery(target).css("top", getTopBottom + "px");
}else{
jQuery(target).css("top", getTop + "px");
}
jQuery('.toggle', this).css('width', jQuery(this).outerWidth());
jQuery('.toggle', this).css('height', jQuery(this).outerHeight());
// Toggle Size
if(jQuery(this).find('.pin')){
var widthThis = jQuery('.pin', this).outerWidth(),
heightThis = jQuery('.pin', this).outerHeight();
jQuery('.toggle', this).css('width', widthThis);
jQuery('.toggle', this).css('height', heightThis);
}
});
}
};
//----------------------------------------//
// Scalize Plugin
//----------------------------------------//
jQuery.fn.scalize = function(options){
return scaling.init(this, options);
};
}(jQuery));
function getBrowserName() {
var name = "Unknown";
if(navigator.userAgent.indexOf("MSIE")!=-1){
name = "MSIE";
}
else if(navigator.userAgent.indexOf("Firefox")!=-1){
name = "Firefox";
}
else if(navigator.userAgent.indexOf("Opera")!=-1){
name = "Opera";
}
else if(navigator.userAgent.indexOf("Chrome") != -1){
name = "Chrome";
}
else if(navigator.userAgent.indexOf("Safari")!=-1){
name = "Safari";
}
return name;
}
Add this to your initialisation:
getSelectorElement: function(el) {
$('.item-point.active').not($(el)[0]).find('.toggle').click();
}
This hooks into the getSelectorElement method in the Scalize plugin and triggers a click on any active (open) elements that don't match the most recently clicked item.
Add it like so:
$(document).ready(function(){
$('.scalize').scalize({
styleSelector: 'circle',
animationPopoverIn: 'fadeIn',
animationPopoverOut: 'fadeOut',
animationSelector: 'pulse2',
getSelectorElement: function(el) {
$('.item-point.active').not($(el)[0]).find('.toggle').click();
}
});
});
Note, because this is hooking into existing methods in the plugin it's a little safer (no unpredictable side effects, plus you get the intended transition out on the disappearing elements). Fiddle.
I've modified your jsFiddle to work.
TL;DR: Anytime an point is clicked, if there are other active siblings, loop over them and hide their popups.
It isn't a pretty way of doing it but it is working in the Fiddle.
$('.scalize').on('click', '.item-point', (function() {
$(this).siblings('.item-point.active').each(function() {
var popover = $(this).data('popover');
$(popover).removeClass('fadeIn').css({
'display': 'none'
});
$(this).removeClass('active');
});
}));

How do i change default orientation in infovis spacetree?

I'm trying to change the default orientation in a space tree but can't figure out where to add:
st.switchPosition("top", "animate", {
onComplete: function() {
alert('completed!');
}
});
So that the tree will start from the top instead of the default of right.
In the examples i've seen, the switchPosition is only used with an event handler, which i do not intend to have.
So in the example (taken from the infovis site:Infovis - spacetree ), where should i add the code (or any code) in order to change the default orientation?
var labelType, useGradients, nativeTextSupport, animate;
(function() {
var ua = navigator.userAgent,
iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
typeOfCanvas = typeof HTMLCanvasElement,
nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
textSupport = nativeCanvasSupport
&& (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
//I'm setting this based on the fact that ExCanvas provides text support for IE
//and that as of today iPhone/iPad current text support is lame
labelType = (!nativeCanvasSupport || (textSupport && !iStuff))? 'Native' : 'HTML';
nativeTextSupport = labelType == 'Native';
useGradients = nativeCanvasSupport;
animate = !(iStuff || !nativeCanvasSupport);
})();
var Log = {
elem: false,
write: function(text){
if (!this.elem)
this.elem = document.getElementById('log');
this.elem.innerHTML = text;
this.elem.style.left = (500 - this.elem.offsetWidth / 2) + 'px';
}
};
function init(){
//init data
var json = {....removed due to space here in the group....}
//end
//A client-side tree generator
var getTree = (function() {
var i = 0;
return function(nodeId, level) {
var subtree = eval('(' + json.replace(/id:\"([a-zA-Z0-9]+)\"/g,
function(all, match) {
return "id:\"" + match + "_" + i + "\""
}) + ')');
$jit.json.prune(subtree, level); i++;
return {
'id': nodeId,
'children': subtree.children
};
};
})();
//Implement a node rendering function called 'nodeline' that plots a straight line
//when contracting or expanding a subtree.
$jit.ST.Plot.NodeTypes.implement({
'nodeline': {
'render': function(node, canvas, animating) {
if(animating === 'expand' || animating === 'contract') {
var pos = node.pos.getc(true), nconfig = this.node, data = node.data;
var width = nconfig.width, height = nconfig.height;
var algnPos = this.getAlignedPos(pos, width, height);
var ctx = canvas.getCtx(), ort = this.config.orientation;
ctx.beginPath();
if(ort == 'left' || ort == 'right') {
ctx.moveTo(algnPos.x, algnPos.y + height / 2);
ctx.lineTo(algnPos.x + width, algnPos.y + height / 2);
} else {
ctx.moveTo(algnPos.x + width / 2, algnPos.y);
ctx.lineTo(algnPos.x + width / 2, algnPos.y + height);
}
ctx.stroke();
}
}
}
});
//init Spacetree
//Create a new ST instance
var st = new $jit.ST({
'injectInto': 'infovis',
//set duration for the animation
duration: 800,
//set animation transition type
transition: $jit.Trans.Quart.easeInOut,
//set distance between node and its children
levelDistance: 50,
//set max levels to show. Useful when used with
//the request method for requesting trees of specific depth
levelsToShow: 2,
//set node and edge styles
//set overridable=true for styling individual
//nodes or edges
Node: {
height: 20,
width: 40,
//use a custom
//node rendering function
type: 'nodeline',
color:'#23A4FF',
lineWidth: 2,
align:"center",
overridable: true
},
Edge: {
type: 'bezier',
lineWidth: 2,
color:'#23A4FF',
overridable: true
},
//Add a request method for requesting on-demand json trees.
//This method gets called when a node
//is clicked and its subtree has a smaller depth
//than the one specified by the levelsToShow parameter.
//In that case a subtree is requested and is added to the dataset.
//This method is asynchronous, so you can make an Ajax request for that
//subtree and then handle it to the onComplete callback.
//Here we just use a client-side tree generator (the getTree function).
request: function(nodeId, level, onComplete) {
var ans = getTree(nodeId, level);
onComplete.onComplete(nodeId, ans);
},
onBeforeCompute: function(node){
Log.write("loading " + node.name);
},
onAfterCompute: function(){
Log.write("done");
},
//This method is called on DOM label creation.
//Use this method to add event handlers and styles to
//your node.
onCreateLabel: function(label, node){
label.id = node.id;
label.innerHTML = node.name;
label.onclick = function(){
st.onClick(node.id);
};
//set label styles
var style = label.style;
style.width = 40 + 'px';
style.height = 17 + 'px';
style.cursor = 'pointer';
style.color = '#fff';
//style.backgroundColor = '#1a1a1a';
style.fontSize = '0.8em';
style.textAlign= 'center';
style.textDecoration = 'underline';
style.paddingTop = '3px';
},
//This method is called right before plotting
//a node. It's useful for changing an individual node
//style properties before plotting it.
//The data properties prefixed with a dollar
//sign will override the global node style properties.
onBeforePlotNode: function(node){
//add some color to the nodes in the path between the
//root node and the selected node.
if (node.selected) {
node.data.$color = "#ff7";
}
else {
delete node.data.$color;
}
},
//This method is called right before plotting
//an edge. It's useful for changing an individual edge
//style properties before plotting it.
//Edge data proprties prefixed with a dollar sign will
//override the Edge global style properties.
onBeforePlotLine: function(adj){
if (adj.nodeFrom.selected && adj.nodeTo.selected) {
adj.data.$color = "#eed";
adj.data.$lineWidth = 3;
}
else {
delete adj.data.$color;
delete adj.data.$lineWidth;
}
}
});
//load json data
st.loadJSON(eval( '(' + json + ')' ));
//compute node positions and layout
st.compute();
//emulate a click on the root node.
st.onClick(st.root);
//end
//Add event handlers to switch spacetree orientation. - Which i do not want...
// function get(id) {
// return document.getElementById(id);
// };
// var top = get('r-top'),
// left = get('r-left'),
// bottom = get('r-bottom'),
// right = get('r-right');
// function changeHandler() {
// if(this.checked) {
// top.disabled = bottom.disabled = right.disabled = left.disabled = true;
// st.switchPosition(this.value, "animate", {
// onComplete: function(){
// top.disabled = bottom.disabled = right.disabled = left.disabled = false;
// }
// });
// }
// };
// top.onchange = left.onchange = bottom.onchange = right.onchange = changeHandler;
//end
}
You can drop in orientation:'top', shortly into the new $jit.ST function, ie:
var st = new $jit.ST({
//id of viz container element
injectInto: 'infovis',
//SET THE TREE TO VERTICAL
orientation:"top",
//set duration for the animation
duration: 800,
Source: https://groups.google.com/forum/#!searchin/javascript-information-visualization-toolkit/top/javascript-information-visualization-toolkit/MhXSXJUmaIk/V5JNwSe359gJ

How to drag an image to move it smoothly on screen, using jquery in ie8

I am working on a project where we can move an image like in google map,, it works perfectly in crome,ff and above ie9, but when i checked in ie8 the image is not moving smoothly,it takes a 2 to 3 sec of time to move.
/* Map dragging */
var previousX;
var previousY;
var previousLeft;
var previousTop;
var cids = self.data.cuLocation;
var lumids = self.data.lumLocation;
$('#MapView img').css( 'cursor', 'pointer' );
$("#MapView img").mousedown(function(e) {
//console.log("mousedown");
e.preventDefault();
drag.state = true;
previousX = e.originalEvent.clientX;
previousY = e.originalEvent.clientY;
previousLeft = $("#MapView img").position().left;
previousTop = $("#MapView img").position().top;
});
$("#MapView img").mousemove(function(e) {
var old_pos = self.getPosition();
if (drag.state) {
e.preventDefault();
drag.x = e.originalEvent.clientX - previousX;
drag.y = e.originalEvent.clientY - previousY;
var cur_position = $("#MapView img").position();
var new_left = cur_position.left + drag.x;
var new_top = cur_position.top + drag.y;
previousX = e.originalEvent.clientX;
previousY = e.originalEvent.clientY;
}
});
$("#MapView img").mouseleave(function(e) {
//console.log("mouseleave");
drag.state = false;
});
$(document).mouseup(function(e) {
// alert("mouseup");
drag.state = false;
});
Use the following Link for your better understanding in Draggable event so than you can use it to Drag your Image wherever you want.
http://jqueryui.com/draggable/
and for Drap & Drop of one element onto other element ::
http://jqueryui.com/draggable/#snap-to

textarea autogrow functionality jitters with every keystroke

I was playing around with the jquery autogrow plugin, which expands the height of the text automatically as the text needs it. The problem is that with every key down, the bottom border of the textarea jitters in a noticeable way. I'm not sure what the problem could be, so I'm going to go out on a limb and post the 132 lines of this GPL plugin here. Any hints where the problem could be or how to circumvent it?
/*
Auto Expanding Text Area (1.2.2) by Chrys Bader */
(function(jQuery) {
var self = null;
jQuery.fn.autogrow = function(o){
return this.each(function() {
new jQuery.autogrow(this, o);
});
};
/**
* The autogrow object.
*
* #constructor
* #name jQuery.autogrow
* #param Object e The textarea to create the autogrow for.
* #param Hash o A set of key/value pairs to set as configuration properties.
* #cat Plugins/autogrow
*/
jQuery.autogrow = function (e, o) {
this.options = o || {};
this.dummy = null;
this.interval = null;
this.line_height = this.options.lineHeight || parseInt(jQuery(e).css('line-height'));
this.min_height = this.options.minHeight || parseInt(jQuery(e).css('min-height'));
this.max_height = this.options.maxHeight || parseInt(jQuery(e).css('max-height'));;
this.textarea = jQuery(e);
if(this.line_height == NaN) this.line_height = 0;
// Only one textarea activated at a time, the one being used
this.init();
};
jQuery.autogrow.fn = jQuery.autogrow.prototype = { autogrow: '1.2.2' };
jQuery.autogrow.fn.extend = jQuery.autogrow.extend = jQuery.extend;
jQuery.autogrow.fn.extend({ init: function(){
var self = this;
this.textarea.css({overflow: 'hidden', display: 'block'});
this.textarea.bind('focus', function(){ self.startExpand() }).bind('blur', function() { self.stopExpand() });
this.checkExpand();
},
startExpand: function() {
var self = this;
this.interval = window.setInterval(function() { self.checkExpand()}, 400); },
stopExpand: function() { clearInterval(this.interval); },
checkExpand: function() {
if (this.dummy == null) {
this.dummy = jQuery('<div></div>');
this.dummy.css({
'font-size' : this.textarea.css('font-size'),
'font-family': this.textarea.css('font-family'),
'width' : this.textarea.css('width'),
'padding' : this.textarea.css('padding'),
'line-height': this.line_height + 'px',
'overflow-x' : 'hidden',
'position' : 'absolute',
'top' : 0,
'left' : -9999
}).appendTo('body');
}
// Strip HTML tags
var html = this.textarea.val().replace(/(<|>)/g,'');
// IE is different, as per usual
if ($.browser.msie){
html = html.replace(/\n/g, '<BR>new');
} else {
html = html.replace(/\n/g, '<br>new');
}
if (this.dummy.html() != html){
this.dummy.html(html);
if (this.max_height > 0 && (this.dummy.height() + this.line_height > this.max_height)){
this.textarea.css('overflow-y', 'auto');
} else {
this.textarea.css('overflow-y', 'hidden');
if (this.textarea.height() < this.dummy.height() + this.line_height || (this.dummy.height() < this.textarea.height())) {
this.textarea.animate({height: (this.dummy.height() + this.line_height) + 'px'}, 100);
}
}
}
}
});
})(jQuery);
In regard to jeerose's comment:
http://www.aclevercookie.com/aclevercookiecom-breached-problem-resolved/
It has been brought to my attention by
visitors that their virus protection
goes off when they come to this blog.
I investigated the matter and found
that harmful code had been injected
into the source of the site.
This has been resolved and measures
have been taken to increase the
security of the site.
Thanks for the report, and I apologize
for the alarm.
Which doesn't seem to be true. As my antivirus still fires when opening that site

Categories

Resources