Callback function to add newly loaded images to a roll - javascript

Hi I'm working on a site with a infinite scroll script and am trying to figure out how to add a callback for Image Lightbox:
http://osvaldas.info/image-lightbox-responsive-touch-friendly
I've managed to get the images on the second page to work with image light box and have them styled with the same variables using this:
$(function () {
$('a[data-imagelightbox="d"]').imageLightbox({
onStart: function () {
overlayOn();
},
onLoadStart: function () {
captionOff();
activityIndicatorOn();
},
onLoadEnd: function () {
captionOn();
activityIndicatorOff();
},
onEnd: function () {
captionOff();
overlayOff();
activityIndicatorOff();
}
});
});
My problem is that while the images from "page two" can be viewed within the lightbox, they are not added to the gallery/roll for the user to cycle/navigate through. When the user views an image from "page two" and attempts to cycle through they can only view images from "page one".
Anyone know what script I should be using to get the images refreshed/added after infinite scroll loads more content? Thanks in advance!!
Here is the full js for the Image Lightbox:
var cssTransitionSupport = function () {
var s = document.body || document.documentElement,
s = s.style;
if (s.WebkitTransition == '') return '-webkit-';
if (s.MozTransition == '') return '-moz-';
if (s.OTransition == '') return '-o-';
if (s.transition == '') return '';
return false;
},
isCssTransitionSupport = cssTransitionSupport() === false ? false : true,
cssTransitionTranslateX = function (element, positionX, speed) {
var options = {}, prefix = cssTransitionSupport();
options[prefix + 'transform'] = 'translateX(' + positionX + ')';
options[prefix + 'transition'] = prefix + 'transform ' + speed + 's linear';
element.css(options);
},
hasTouch = ('ontouchstart' in window),
hasPointers = window.navigator.pointerEnabled || window.navigator.msPointerEnabled,
wasTouched = function (event) {
if (hasTouch) return true;
if (!hasPointers || typeof event === 'undefined' || typeof event.pointerType === 'undefined') return false;
if (typeof event.MSPOINTER_TYPE_MOUSE !== 'undefined') {
if (event.MSPOINTER_TYPE_MOUSE != event.pointerType) return true;
} else if (event.pointerType != 'mouse') return true;
return false;
};
$.fn.imageLightbox = function (options) {
var options = $.extend({
selector: 'id="imagelightbox"',
allowedTypes: 'png|jpg|jpeg|gif',
animationSpeed: 250,
preloadNext: true,
enableKeyboard: true,
quitOnEnd: false,
quitOnImgClick: false,
quitOnDocClick: true,
onStart: false,
onEnd: false,
onLoadStart: false,
onLoadEnd: false
},
options),
targets = $([]),
target = $(),
image = $(),
imageWidth = 0,
imageHeight = 0,
swipeDiff = 0,
inProgress = false,
isTargetValid = function (element) {
return $(element).prop('tagName').toLowerCase() == 'a' && (new RegExp('\.(' + options.allowedTypes + ')$', 'i')).test($(element).attr('href'));
},
setImage = function () {
if (!image.length) return true;
var screenWidth = $(window).width() * 0.8,
screenHeight = $(window).height() * 0.9,
tmpImage = new Image();
tmpImage.src = image.attr('src');
tmpImage.onload = function () {
imageWidth = tmpImage.width;
imageHeight = tmpImage.height;
if (imageWidth > screenWidth || imageHeight > screenHeight) {
var ratio = imageWidth / imageHeight > screenWidth / screenHeight ? imageWidth / screenWidth : imageHeight / screenHeight;
imageWidth /= ratio;
imageHeight /= ratio;
}
image.css({
'width': imageWidth + 'px',
'height': imageHeight + 'px',
'top': ($(window).height() - imageHeight) / 2 + 'px',
'left': ($(window).width() - imageWidth) / 2 + 'px'
});
};
},
loadImage = function (direction) {
if (inProgress) return false;
direction = typeof direction === 'undefined' ? false : direction == 'left' ? 1 : -1;
if (image.length) {
if (direction !== false && (targets.length < 2 || (options.quitOnEnd === true && ((direction === -1 && targets.index(target) == 0) || (direction === 1 && targets.index(target) == targets.length - 1))))) {
quitLightbox();
return false;
}
var params = {
'opacity': 0
};
if (isCssTransitionSupport) cssTransitionTranslateX(image, (100 * direction) - swipeDiff + 'px', options.animationSpeed / 1000);
else params.left = parseInt(image.css('left')) + 100 * direction + 'px';
image.animate(params, options.animationSpeed, function () {
removeImage();
});
swipeDiff = 0;
}
inProgress = true;
if (options.onLoadStart !== false) options.onLoadStart();
setTimeout(function () {
image = $('<img ' + options.selector + ' />')
.attr('src', target.attr('href'))
.load(function () {
image.appendTo('body');
setImage();
var params = {
'opacity': 1
};
image.css('opacity', 0);
if (isCssTransitionSupport) {
cssTransitionTranslateX(image, -100 * direction + 'px', 0);
setTimeout(function () {
cssTransitionTranslateX(image, 0 + 'px', options.animationSpeed / 1000)
}, 50);
} else {
var imagePosLeft = parseInt(image.css('left'));
params.left = imagePosLeft + 'px';
image.css('left', imagePosLeft - 100 * direction + 'px');
}
image.animate(params, options.animationSpeed, function () {
inProgress = false;
if (options.onLoadEnd !== false) options.onLoadEnd();
});
if (options.preloadNext) {
var nextTarget = targets.eq(targets.index(target) + 1);
if (!nextTarget.length) nextTarget = targets.eq(0);
$('<img />').attr('src', nextTarget.attr('href')).load();
}
})
.error(function () {
if (options.onLoadEnd !== false) options.onLoadEnd();
})
var swipeStart = 0,
swipeEnd = 0,
imagePosLeft = 0;
image.on(hasPointers ? 'pointerup MSPointerUp' : 'click', function (e) {
e.preventDefault();
if (options.quitOnImgClick) {
quitLightbox();
return false;
}
if (wasTouched(e.originalEvent)) return true;
var posX = (e.pageX || e.originalEvent.pageX) - e.target.offsetLeft;
target = targets.eq(targets.index(target) - (imageWidth / 2 > posX ? 1 : -1));
if (!target.length) target = targets.eq(imageWidth / 2 > posX ? targets.length : 0);
loadImage(imageWidth / 2 > posX ? 'left' : 'right');
})
.on('touchstart pointerdown MSPointerDown', function (e) {
if (!wasTouched(e.originalEvent) || options.quitOnImgClick) return true;
if (isCssTransitionSupport) imagePosLeft = parseInt(image.css('left'));
swipeStart = e.originalEvent.pageX || e.originalEvent.touches[0].pageX;
})
.on('touchmove pointermove MSPointerMove', function (e) {
if (!wasTouched(e.originalEvent) || options.quitOnImgClick) return true;
e.preventDefault();
swipeEnd = e.originalEvent.pageX || e.originalEvent.touches[0].pageX;
swipeDiff = swipeStart - swipeEnd;
if (isCssTransitionSupport) cssTransitionTranslateX(image, -swipeDiff + 'px', 0);
else image.css('left', imagePosLeft - swipeDiff + 'px');
})
.on('touchend touchcancel pointerup pointercancel MSPointerUp MSPointerCancel', function (e) {
if (!wasTouched(e.originalEvent) || options.quitOnImgClick) return true;
if (Math.abs(swipeDiff) > 50) {
target = targets.eq(targets.index(target) - (swipeDiff < 0 ? 1 : -1));
if (!target.length) target = targets.eq(swipeDiff < 0 ? targets.length : 0);
loadImage(swipeDiff > 0 ? 'right' : 'left');
} else {
if (isCssTransitionSupport) cssTransitionTranslateX(image, 0 + 'px', options.animationSpeed / 1000);
else image.animate({
'left': imagePosLeft + 'px'
}, options.animationSpeed / 2);
}
});
}, options.animationSpeed + 100);
},
removeImage = function () {
if (!image.length) return false;
image.remove();
image = $();
},
quitLightbox = function () {
if (!image.length) return false;
image.animate({
'opacity': 0
}, options.animationSpeed, function () {
removeImage();
inProgress = false;
if (options.onEnd !== false) options.onEnd();
});
};
$(window).on('resize', setImage);
if (options.quitOnDocClick) {
$(document).on(hasTouch ? 'touchend' : 'click', function (e) {
if (image.length && !$(e.target).is(image)) quitLightbox();
})
}
if (options.enableKeyboard) {
$(document).on('keyup', function (e) {
if (!image.length) return true;
e.preventDefault();
if (e.keyCode == 27) quitLightbox();
if (e.keyCode == 37 || e.keyCode == 39) {
target = targets.eq(targets.index(target) - (e.keyCode == 37 ? 1 : -1));
if (!target.length) target = targets.eq(e.keyCode == 37 ? targets.length : 0);
loadImage(e.keyCode == 37 ? 'left' : 'right');
}
});
}
$(document).on('click', this.selector, function (e) {
if (!isTargetValid(this)) return true;
e.preventDefault();
if (inProgress) return false;
inProgress = false;
if (options.onStart !== false) options.onStart();
target = $(this);
loadImage();
});
this.each(function () {
if (!isTargetValid(this)) return true;
targets = targets.add($(this));
});
this.switchImageLightbox = function (index) {
var tmpTarget = targets.eq(index);
if (tmpTarget.length) {
var currentIndex = targets.index(target);
target = tmpTarget;
loadImage(index < currentIndex ? 'left' : 'right');
}
return this;
};
this.quitImageLightbox = function () {
quitLightbox();
return this;
};
return this;
};

Firstly,
$(function () {
window.lightbox = $('a[data-imagelightbox="d"]').imageLightbox();
});
At the end of your "imagelightbox.js", Add the below code.
this.quitImageLightbox = function() {
quitLightbox();
return this;
};
this.loadImages = function(images_array) {
targets = images_array;
console.log(targets);
console.log(targets.length);
return this;
};
And when you get newly loaded images
windows.lightbox.loadImages(images_array)
and it should be working...!

Related

Integrate web content page on lightbox

I have two pages: the first contains a button when clicked it appears a lightbox. i want to get the content of the second page an put it on lightbox
page1
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="jquery.colorbox.js"></script>
<link rel="stylesheet" href="colorbox.css" />
<script>
$(document).ready(function () {
$(".inline").colorbox({ inline: true, width: "50%" });
})
</script>
<title></title>
</head>
<body>
<h1>Colorbox Demonstration</h1>
<p><a class='inline' href="#inline_content">Inline HTML</a></p>
<div style='display:none'>
<div id='inline_content' style='padding:10px; background:#fff;'>
<p><strong>This content comes from a hidden element on this page.</strong></p>
<p>The inline option preserves bound JavaScript events and changes, and it puts the content back where it came from when it is closed.</p>
<p><a id="click" href="#" style='padding:5px; background:#ccc;'>btn1</a></p>
</div>
</div>
<div style='display:none'>
<div id='test' style='padding:10px; background:#fff;'>
<p>The inline option preserves bound JavaScript events and changes.</p>
</div>
</div>
</body>
</html>
jquery.colorbox.js
(function ($, document, window) {
var
defaults = {
html: false,
photo: false,
iframe: false,
inline: false,
transition: "elastic",
speed: 300,
fadeOut: 300,
width: false,
initialWidth: "600",
innerWidth: false,
maxWidth: false,
height: false,
initialHeight: "450",
innerHeight: false,
maxHeight: false,
scrolling: true,
opacity: 0.9,
preloading: true,
className: false,
overlayClose: true,
escKey: true,
arrowKey: true,
top: false,
bottom: false,
left: false,
right: false,
fixed: false,
closeButton: true,
fastIframe: true,
open: false,
href: function() {
return $(this).attr('href');
},
createIframe: function() {
var iframe = document.createElement('iframe');
var attrs = $(this).data('cbox-iframe-attrs');
if (typeof attrs === 'object') {
$.each(attrs, function(key, val){
iframe[key] = val;
});
}
return iframe;
}
},
colorbox = 'colorbox',
prefix = 'cbox',
boxElement = prefix + 'Element',
event_open = prefix + '_open',
event_load = prefix + '_load',
event_complete = prefix + '_complete',
event_cleanup = prefix + '_cleanup',
event_closed = prefix + '_closed',
event_purge = prefix + '_purge',
$overlay,
$box,
$wrap,
$content,
$topBorder,
$leftBorder,
$rightBorder,
$bottomBorder,
$related,
$window,
$loaded,
$loadingBay,
$loadingOverlay,
$title,
$current,
$slideshow,
$next,
$prev,
$close,
$groupControls,
$events = $('<a/>'),
settings,
interfaceHeight,
interfaceWidth,
loadedHeight,
loadedWidth,
index,
photo,
open,
active,
closing,
loadingTimer,
publicMethod,
div = "div",
requests = 0,
previousCSS = {},
init;
function $tag(tag, id, css) {
var element = document.createElement(tag);
if (id) {
element.id = prefix + id;
}
if (css) {
element.style.cssText = css;
}
return $(element);
}
function winheight() {
return window.innerHeight ? window.innerHeight : $(window).height();
}
function Settings(element, options) {
if (options !== Object(options)) {
options = {};
}
this.cache = {};
this.el = element;
this.value = function(key) {
var dataAttr;
if (this.cache[key] === undefined) {
dataAttr = $(this.el).attr('data-cbox-'+key);
if (dataAttr !== undefined) {
this.cache[key] = dataAttr;
} else if (options[key] !== undefined) {
this.cache[key] = options[key];
} else if (defaults[key] !== undefined) {
this.cache[key] = defaults[key];
}
}
return this.cache[key];
};
this.get = function(key) {
var value = this.value(key);
return $.isFunction(value) ? value.call(this.el, this) : value;
};
}
function setSize(size, dimension) {
return Math.round((/%/.test(size) ? ((dimension === 'x' ? $window.width() : winheight()) / 100) : 1) * parseInt(size, 10));
}
function setClass(str) {
if (setClass.str !== str) {
$box.add($overlay).removeClass(setClass.str).addClass(str);
setClass.str = str;
}
}
function getRelated(rel) {
index = 0;
if (rel && rel !== false && rel !== 'nofollow') {
$related = $('.' + boxElement).filter(function () {
var options = $.data(this, colorbox);
var settings = new Settings(this, options);
return (settings.get('rel') === rel);
});
index = $related.index(settings.el);
if (index === -1) {
$related = $related.add(settings.el);
index = $related.length - 1;
}
} else {
$related = $(settings.el);
}
}
function trigger(event) {
// for external use
$(document).trigger(event);
// for internal use
$events.triggerHandler(event);
};
function launch(element) {
var options;
if (!closing) {
options = $(element).data(colorbox);
settings = new Settings(element, options);
getRelated(settings.get('rel'));
if (!open) {
open = active = true;
setClass(settings.get('className'));
$box.css({visibility:'hidden', display:'block', opacity:''});
$loaded = $tag(div, 'LoadedContent', 'width:0; height:0; overflow:hidden; visibility:hidden');
$content.css({width:'', height:''}).append($loaded);
interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height();
interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width();
loadedHeight = $loaded.outerHeight(true);
loadedWidth = $loaded.outerWidth(true);
var initialWidth = setSize(settings.get('initialWidth'), 'x');
var initialHeight = setSize(settings.get('initialHeight'), 'y');
var maxWidth = settings.get('maxWidth');
var maxHeight = settings.get('maxHeight');
settings.w = Math.max((maxWidth !== false ? Math.min(initialWidth, setSize(maxWidth, 'x')) : initialWidth) - loadedWidth - interfaceWidth, 0);
settings.h = Math.max((maxHeight !== false ? Math.min(initialHeight, setSize(maxHeight, 'y')) : initialHeight) - loadedHeight - interfaceHeight, 0);
$loaded.css({width:'', height:settings.h});
publicMethod.position();
trigger(event_open);
settings.get('onOpen');
$groupControls.add($title).hide();
$box.focus();
if (settings.get('returnFocus')) {
$events.one(event_closed, function () {
$(settings.el).focus();
});
}
}
var opacity = parseFloat(settings.get('opacity'));
$overlay.css({
opacity: opacity === opacity ? opacity : '',
cursor: settings.get('overlayClose') ? 'pointer' : '',
visibility: 'visible'
}).show();
if (settings.get('closeButton')) {
$close.html(settings.get('close')).appendTo($content);
} else {
$close.appendTo('<div/>');
}
load();
}
}
function appendHTML() {
if (!$box) {
init = false;
$window = $(window);
$box = $tag(div).attr({
id: colorbox,
'class': $.support.opacity === false ? prefix + 'IE' : '',
role: 'dialog',
tabindex: '-1'
}).hide();
$overlay = $tag(div, "Overlay").hide();
$loadingOverlay = $([$tag(div, "LoadingOverlay")[0],$tag(div, "LoadingGraphic")[0]]);
$wrap = $tag(div, "Wrapper");
$content = $tag(div, "Content").append(
$title = $tag(div, "Title"),
$current = $tag(div, "Current"),
$prev = $('<button type="button"/>').attr({id:prefix+'Previous'}),
$next = $('<button type="button"/>').attr({id:prefix+'Next'}),
$slideshow = $tag('button', "Slideshow"),
$loadingOverlay
);
$close = $('<button type="button"/>').attr({id:prefix+'Close'});
$wrap.append(
$tag(div).append(
$tag(div, "TopLeft"),
$topBorder = $tag(div, "TopCenter"),
$tag(div, "TopRight")
),
$tag(div, false, 'clear:left').append(
$leftBorder = $tag(div, "MiddleLeft"),
$content,
$rightBorder = $tag(div, "MiddleRight")
),
$tag(div, false, 'clear:left').append(
$tag(div, "BottomLeft"),
$bottomBorder = $tag(div, "BottomCenter"),
$tag(div, "BottomRight")
)
).find('div div').css({'float': 'left'});
$loadingBay = $tag(div, false, 'position:absolute; width:9999px; visibility:hidden; display:none; max-width:none;');
$groupControls = $next.add($prev).add($current).add($slideshow);
}
if (document.body && !$box.parent().length) {
$(document.body).append($overlay, $box.append($wrap, $loadingBay));
}
}
function addBindings() {
function clickHandler(e) {
if (!(e.which > 1 || e.shiftKey || e.altKey || e.metaKey || e.ctrlKey)) {
e.preventDefault();
launch(this);
}
}
if ($box) {
if (!init) {
init = true;
$next.click(function () {
publicMethod.next();
});
$prev.click(function () {
publicMethod.prev();
});
$close.click(function () {
publicMethod.close();
});
$overlay.click(function () {
if (settings.get('overlayClose')) {
publicMethod.close();
}
});
$(document).bind('keydown.' + prefix, function (e) {
var key = e.keyCode;
if (open && settings.get('escKey') && key === 27) {
e.preventDefault();
publicMethod.close();
}
if (open && settings.get('arrowKey') && $related[1] && !e.altKey) {
if (key === 37) {
e.preventDefault();
$prev.click();
} else if (key === 39) {
e.preventDefault();
$next.click();
}
}
});
if ($.isFunction($.fn.on)) {
$(document).on('click.'+prefix, '.'+boxElement, clickHandler);
} else {
$('.'+boxElement).live('click.'+prefix, clickHandler);
}
}
return true;
}
return false;
}
if ($[colorbox]) {
return;
}
$(appendHTML);
publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) {
var settings;
var $obj = this;
options = options || {};
if ($.isFunction($obj)) {
$obj = $('<a/>');
options.open = true;
}
if (!$obj[0]) {
return $obj;
}
appendHTML();
if (addBindings()) {
if (callback) {
options.onComplete = callback;
}
$obj.each(function () {
var old = $.data(this, colorbox) || {};
$.data(this, colorbox, $.extend(old, options));
}).addClass(boxElement);
settings = new Settings($obj[0], options);
if (settings.get('open')) {
launch($obj[0]);
}
}
return $obj;
};
publicMethod.position = function (speed, loadedCallback) {
var
css,
top = 0,
left = 0,
offset = $box.offset(),
scrollTop,
scrollLeft;
$window.unbind('resize.' + prefix);
$box.css({top: -9e4, left: -9e4});
scrollTop = $window.scrollTop();
scrollLeft = $window.scrollLeft();
if (settings.get('fixed')) {
offset.top -= scrollTop;
offset.left -= scrollLeft;
$box.css({position: 'fixed'});
} else {
top = scrollTop;
left = scrollLeft;
$box.css({position: 'absolute'});
}
if (settings.get('right') !== false) {
left += Math.max($window.width() - settings.w - loadedWidth - interfaceWidth - setSize(settings.get('right'), 'x'), 0);
} else if (settings.get('left') !== false) {
left += setSize(settings.get('left'), 'x');
} else {
left += Math.round(Math.max($window.width() - settings.w - loadedWidth - interfaceWidth, 0) / 2);
}
if (settings.get('bottom') !== false) {
top += Math.max(winheight() - settings.h - loadedHeight - interfaceHeight - setSize(settings.get('bottom'), 'y'), 0);
} else if (settings.get('top') !== false) {
top += setSize(settings.get('top'), 'y');
} else {
top += Math.round(Math.max(winheight() - settings.h - loadedHeight - interfaceHeight, 0) / 2);
}
$box.css({top: offset.top, left: offset.left, visibility:'visible'});
$wrap[0].style.width = $wrap[0].style.height = "9999px";
function modalDimensions() {
$topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = (parseInt($box[0].style.width,10) - interfaceWidth)+'px';
$content[0].style.height = $leftBorder[0].style.height = $rightBorder[0].style.height = (parseInt($box[0].style.height,10) - interfaceHeight)+'px';
}
css = {width: settings.w + loadedWidth + interfaceWidth, height: settings.h + loadedHeight + interfaceHeight, top: top, left: left};
if (speed) {
var tempSpeed = 0;
$.each(css, function(i){
if (css[i] !== previousCSS[i]) {
tempSpeed = speed;
return;
}
});
speed = tempSpeed;
}
previousCSS = css;
if (!speed) {
$box.css(css);
}
$box.dequeue().animate(css, {
duration: speed || 0,
complete: function () {
modalDimensions();
active = false;
$wrap[0].style.width = (settings.w + loadedWidth + interfaceWidth) + "px";
$wrap[0].style.height = (settings.h + loadedHeight + interfaceHeight) + "px";
if (settings.get('reposition')) {
setTimeout(function () {
$window.bind('resize.' + prefix, publicMethod.position);
}, 1);
}
if ($.isFunction(loadedCallback)) {
loadedCallback();
}
},
step: modalDimensions
});
};
publicMethod.resize = function (options) {
var scrolltop;
if (open) {
options = options || {};
if (options.width) {
settings.w = setSize(options.width, 'x') - loadedWidth - interfaceWidth;
}
if (options.innerWidth) {
settings.w = setSize(options.innerWidth, 'x');
}
$loaded.css({width: settings.w});
if (options.height) {
settings.h = setSize(options.height, 'y') - loadedHeight - interfaceHeight;
}
if (options.innerHeight) {
settings.h = setSize(options.innerHeight, 'y');
}
if (!options.innerHeight && !options.height) {
scrolltop = $loaded.scrollTop();
$loaded.css({height: "auto"});
settings.h = $loaded.height();
}
$loaded.css({height: settings.h});
if(scrolltop) {
$loaded.scrollTop(scrolltop);
}
publicMethod.position(settings.get('transition') === "none" ? 0 : settings.get('speed'));
}
};
publicMethod.prep = function (object) {
if (!open) {
return;
}
var callback, speed = settings.get('transition') === "none" ? 0 : settings.get('speed');
$loaded.remove();
$loaded = $tag(div, 'LoadedContent').append(object);
function getWidth() {
settings.w = settings.w || $loaded.width();
settings.w = settings.mw && settings.mw < settings.w ? settings.mw : settings.w;
return settings.w;
}
function getHeight() {
settings.h = settings.h || $loaded.height();
settings.h = settings.mh && settings.mh < settings.h ? settings.mh : settings.h;
return settings.h;
}
$loaded.hide()
.appendTo($loadingBay.show())
.css({width: getWidth(), overflow: settings.get('scrolling') ? 'auto' : 'hidden'})
.css({height: getHeight()})
.prependTo($content);
$loadingBay.hide();
$(photo).css({'float': 'none'});
setClass(settings.get('className'));
callback = function () {
var total = $related.length,
iframe,
complete;
if (!open) {
return;
}
function removeFilter() {
if ($.support.opacity === false) {
$box[0].style.removeAttribute('filter');
}
}
complete = function () {
clearTimeout(loadingTimer);
$loadingOverlay.hide();
trigger(event_complete);
settings.get('onComplete');
};
$title.html(settings.get('title')).show();
$loaded.show();
if (total > 1) {
if (typeof settings.get('current') === "string") {
$current.html(settings.get('current').replace('{current}', index + 1).replace('{total}', total)).show();
}
$next[(settings.get('loop') || index < total - 1) ? "show" : "hide"]().html(settings.get('next'));
$prev[(settings.get('loop') || index) ? "show" : "hide"]().html(settings.get('previous'));
} else {
$groupControls.hide();
}
if (settings.get('iframe')) {
iframe = settings.get('createIframe');
if (!settings.get('scrolling')) {
iframe.scrolling = "no";
}
$(iframe)
.attr({
src: settings.get('href'),
'class': prefix + 'Iframe'
})
.one('load', complete)
.appendTo($loaded);
$events.one(event_purge, function () {
iframe.src = "//about:blank";
});
if (settings.get('fastIframe')) {
$(iframe).trigger('load');
}
} else {
complete();
}
if (settings.get('transition') === 'fade') {
$box.fadeTo(speed, 1, removeFilter);
} else {
removeFilter();
}
};
if (settings.get('transition') === 'fade') {
$box.fadeTo(speed, 0, function () {
publicMethod.position(0, callback);
});
} else {
publicMethod.position(speed, callback);
}
};
function load () {
var href, setResize, prep = publicMethod.prep, $inline, request = ++requests;
active = true;
photo = false;
trigger(event_purge);
trigger(event_load);
settings.get('onLoad');
settings.h = settings.get('height') ?
setSize(settings.get('height'), 'y') - loadedHeight - interfaceHeight :
settings.get('innerHeight') && setSize(settings.get('innerHeight'), 'y');
settings.w = settings.get('width') ?
setSize(settings.get('width'), 'x') - loadedWidth - interfaceWidth :
settings.get('innerWidth') && setSize(settings.get('innerWidth'), 'x');
settings.mw = settings.w;
settings.mh = settings.h;
if (settings.get('maxWidth')) {
settings.mw = setSize(settings.get('maxWidth'), 'x') - loadedWidth - interfaceWidth;
settings.mw = settings.w && settings.w < settings.mw ? settings.w : settings.mw;
}
if (settings.get('maxHeight')) {
settings.mh = setSize(settings.get('maxHeight'), 'y') - loadedHeight - interfaceHeight;
settings.mh = settings.h && settings.h < settings.mh ? settings.h : settings.mh;
}
href = settings.get('href');
loadingTimer = setTimeout(function () {
$loadingOverlay.show();
}, 100);
if (settings.get('inline')) {
var $target = $(href);
$inline = $('<div>').hide().insertBefore($target);
$events.one(event_purge, function () {
$inline.replaceWith($target);
});
prep($target);
} else if (settings.get('iframe')) {
prep(" ");
} else if (settings.get('html')) {
prep(settings.get('html'));
}
}
publicMethod.next = function () {
if (!active && $related[1] && (settings.get('loop') || $related[index + 1])) {
index = getIndex(1);
launch($related[index]);
}
};
publicMethod.close = function () {
if (open && !closing) {
closing = true;
open = false;
trigger(event_cleanup);
settings.get('onCleanup');
$window.unbind('.' + prefix);
$overlay.fadeTo(settings.get('fadeOut') || 0, 0);
$box.stop().fadeTo(settings.get('fadeOut') || 0, 0, function () {
$box.hide();
$overlay.hide();
trigger(event_purge);
$loaded.remove();
setTimeout(function () {
closing = false;
trigger(event_closed);
settings.get('onClosed');
}, 1);
});
}
};
publicMethod.element = function () {
return $(settings.el);
};
}(jQuery, document, window));
page2
<html>
<head>
<meta charset=utf-8"/>
<title></title>
</head>
<body>
dfdfdffdfdfdf
</body>
</html>
I would like to integrate the content of html page2 on a lightbox of page1
try to use it,
iframe: true, when $(document).ready function

get element height inside flexslider

I was hoping you could help me with this. I am trying to use some javascript to find the height of an element inside of a flexslider . There are two catches. When I try a regular
function getHeight(){
var h = document.getElementById("id-height").style.height;
alert(h + " px");
with a body onload="getHeight()" the height that I get on the element is not coming up. I am guessing because the function is being called before all the elements in the slider load but that's just a guess. The other catch is that I need to recall the function every time the slider changes pictures. Basically what I'm trying to achieve is to add a top margin on an element inside a flexslider so that it is middle-aligned vertically. To see what I'm talking about, please go to http://evergreenbusinessbuilders.businesscatalyst.com and look at the main slider at the very top under the navigation.
Here is the jquery for the slider (as i got it from woothemes):
/*
* jQuery FlexSlider v1.8
* http://www.woothemes.com/flexslider/
*
* Copyright 2012 WooThemes
* Free to use under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Contrib: Darin Richardson
*/
;(function ($) {
//FlexSlider: Object Instance
$.flexslider = function(el, options) {
var slider = el;
slider.init = function() {
slider.vars = $.extend({}, $.flexslider.defaults, options);
slider.data('flexslider', true);
slider.container = $('.slides', slider).first();
slider.slides = $('.slides:first > li', slider);
slider.count = slider.slides.length;
slider.animating = false;
slider.currentSlide = slider.vars.slideToStart;
slider.animatingTo = slider.currentSlide;
slider.atEnd = (slider.currentSlide == 0) ? true : false;
slider.eventType = ('ontouchstart' in document.documentElement) ? 'touchstart' : 'click';
slider.cloneCount = 0;
slider.cloneOffset = 0;
slider.manualPause = false;
slider.vertical = (slider.vars.slideDirection == "vertical");
slider.prop = (slider.vertical) ? "top" : "marginLeft";
slider.args = {};
//Test for webbkit CSS3 Animations
slider.transitions = "webkitTransition" in document.body.style;
if (slider.transitions) slider.prop = "-webkit-transform";
//Test for controlsContainer
if (slider.vars.controlsContainer != "") {
slider.controlsContainer = $(slider.vars.controlsContainer).eq($('.slides').index(slider.container));
slider.containerExists = slider.controlsContainer.length > 0;
}
//Test for manualControls
if (slider.vars.manualControls != "") {
slider.manualControls = $(slider.vars.manualControls, ((slider.containerExists) ? slider.controlsContainer : slider));
slider.manualExists = slider.manualControls.length > 0;
}
///////////////////////////////////////////////////////////////////
// FlexSlider: Randomize Slides
if (slider.vars.randomize) {
slider.slides.sort(function() { return (Math.round(Math.random())-0.5); });
slider.container.empty().append(slider.slides);
}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
// FlexSlider: Slider Animation Initialize
if (slider.vars.animation.toLowerCase() == "slide") {
if (slider.transitions) {
slider.setTransition(0);
}
slider.css({"overflow": "hidden"});
if (slider.vars.animationLoop) {
slider.cloneCount = 2;
slider.cloneOffset = 1;
slider.container.append(slider.slides.filter(':first').clone().addClass('clone')).prepend(slider.slides.filter(':last').clone().addClass('clone'));
}
//create newSlides to capture possible clones
slider.newSlides = $('.slides:first > li', slider);
var sliderOffset = (-1 * (slider.currentSlide + slider.cloneOffset));
if (slider.vertical) {
slider.newSlides.css({"display": "block", "width": "100%", "float": "left"});
slider.container.height((slider.count + slider.cloneCount) * 200 + "%").css("position", "absolute").width("100%");
//Timeout function to give browser enough time to get proper height initially
setTimeout(function() {
slider.css({"position": "relative"}).height(slider.slides.filter(':first').height());
slider.args[slider.prop] = (slider.transitions) ? "translate3d(0," + sliderOffset * slider.height() + "px,0)" : sliderOffset * slider.height() + "px";
slider.container.css(slider.args);
}, 100);
} else {
slider.args[slider.prop] = (slider.transitions) ? "translate3d(" + sliderOffset * slider.width() + "px,0,0)" : sliderOffset * slider.width() + "px";
slider.container.width((slider.count + slider.cloneCount) * 200 + "%").css(slider.args);
//Timeout function to give browser enough time to get proper width initially
setTimeout(function() {
slider.newSlides.width(slider.width()).css({"float": "left", "display": "block"});
}, 100);
}
} else { //Default to fade
//Not supporting fade CSS3 transitions right now
slider.transitions = false;
slider.slides.css({"width": "100%", "float": "left", "marginRight": "-100%"}).eq(slider.currentSlide).fadeIn(slider.vars.animationDuration);
}
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
// FlexSlider: Control Nav
if (slider.vars.controlNav) {
if (slider.manualExists) {
slider.controlNav = slider.manualControls;
} else {
var controlNavScaffold = $('<ol class="flex-control-nav"></ol>');
var j = 1;
for (var i = 0; i < slider.count; i++) {
controlNavScaffold.append('<li><a>' + j + '</a></li>');
j++;
}
if (slider.containerExists) {
$(slider.controlsContainer).append(controlNavScaffold);
slider.controlNav = $('.flex-control-nav li a', slider.controlsContainer);
} else {
slider.append(controlNavScaffold);
slider.controlNav = $('.flex-control-nav li a', slider);
}
}
slider.controlNav.eq(slider.currentSlide).addClass('active');
slider.controlNav.bind(slider.eventType, function(event) {
event.preventDefault();
if (!$(this).hasClass('active')) {
(slider.controlNav.index($(this)) > slider.currentSlide) ? slider.direction = "next" : slider.direction = "prev";
slider.flexAnimate(slider.controlNav.index($(this)), slider.vars.pauseOnAction);
}
});
}
///////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//FlexSlider: Direction Nav
if (slider.vars.directionNav) {
var directionNavScaffold = $('<ul class="flex-direction-nav"><li><a class="prev" href="#">' + slider.vars.prevText + '</a></li><li><a class="next" href="#">' + slider.vars.nextText + '</a></li></ul>');
if (slider.containerExists) {
$(slider.controlsContainer).append(directionNavScaffold);
slider.directionNav = $('.flex-direction-nav li a', slider.controlsContainer);
} else {
slider.append(directionNavScaffold);
slider.directionNav = $('.flex-direction-nav li a', slider);
}
//Set initial disable styles if necessary
if (!slider.vars.animationLoop) {
if (slider.currentSlide == 0) {
slider.directionNav.filter('.prev').addClass('disabled');
} else if (slider.currentSlide == slider.count - 1) {
slider.directionNav.filter('.next').addClass('disabled');
}
}
slider.directionNav.bind(slider.eventType, function(event) {
event.preventDefault();
var target = ($(this).hasClass('next')) ? slider.getTarget('next') : slider.getTarget('prev');
if (slider.canAdvance(target)) {
slider.flexAnimate(target, slider.vars.pauseOnAction);
}
});
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//FlexSlider: Keyboard Nav
if (slider.vars.keyboardNav && $('ul.slides').length == 1) {
function keyboardMove(event) {
if (slider.animating) {
return;
} else if (event.keyCode != 39 && event.keyCode != 37){
return;
} else {
if (event.keyCode == 39) {
var target = slider.getTarget('next');
} else if (event.keyCode == 37){
var target = slider.getTarget('prev');
}
if (slider.canAdvance(target)) {
slider.flexAnimate(target, slider.vars.pauseOnAction);
}
}
}
$(document).bind('keyup', keyboardMove);
}
//////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
// FlexSlider: Mousewheel interaction
if (slider.vars.mousewheel) {
slider.mousewheelEvent = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel";
slider.bind(slider.mousewheelEvent, function(e) {
e.preventDefault();
e = e ? e : window.event;
var wheelData = e.detail ? e.detail * -1 : e.wheelDelta / 40,
target = (wheelData < 0) ? slider.getTarget('next') : slider.getTarget('prev');
if (slider.canAdvance(target)) {
slider.flexAnimate(target, slider.vars.pauseOnAction);
}
});
}
///////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//FlexSlider: Slideshow Setup
if (slider.vars.slideshow) {
//pauseOnHover
if (slider.vars.pauseOnHover && slider.vars.slideshow) {
slider.hover(function() {
slider.pause();
}, function() {
if (!slider.manualPause) {
slider.resume();
}
});
}
//Initialize animation
slider.animatedSlides = setInterval(slider.animateSlides, slider.vars.slideshowSpeed);
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//FlexSlider: Pause/Play
if (slider.vars.pausePlay) {
var pausePlayScaffold = $('<div class="flex-pauseplay"><span></span></div>');
if (slider.containerExists) {
slider.controlsContainer.append(pausePlayScaffold);
slider.pausePlay = $('.flex-pauseplay span', slider.controlsContainer);
} else {
slider.append(pausePlayScaffold);
slider.pausePlay = $('.flex-pauseplay span', slider);
}
var pausePlayState = (slider.vars.slideshow) ? 'pause' : 'play';
slider.pausePlay.addClass(pausePlayState).text((pausePlayState == 'pause') ? slider.vars.pauseText : slider.vars.playText);
slider.pausePlay.bind(slider.eventType, function(event) {
event.preventDefault();
if ($(this).hasClass('pause')) {
slider.pause();
slider.manualPause = true;
} else {
slider.resume();
slider.manualPause = false;
}
});
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//FlexSlider:Touch Swip Gestures
//Some brilliant concepts adapted from the following sources
//Source: TouchSwipe - http://www.netcu.de/jquery-touchwipe-iphone-ipad-library
//Source: SwipeJS - http://swipejs.com
if ('ontouchstart' in document.documentElement) {
//For brevity, variables are named for x-axis scrolling
//The variables are then swapped if vertical sliding is applied
//This reduces redundant code...I think :)
//If debugging, recognize variables are named for horizontal scrolling
var startX,
startY,
offset,
cwidth,
dx,
startT,
scrolling = false;
slider.each(function() {
if ('ontouchstart' in document.documentElement) {
this.addEventListener('touchstart', onTouchStart, false);
}
});
function onTouchStart(e) {
if (slider.animating) {
e.preventDefault();
} else if (e.touches.length == 1) {
slider.pause();
cwidth = (slider.vertical) ? slider.height() : slider.width();
startT = Number(new Date());
offset = (slider.vertical) ? (slider.currentSlide + slider.cloneOffset) * slider.height() : (slider.currentSlide + slider.cloneOffset) * slider.width();
startX = (slider.vertical) ? e.touches[0].pageY : e.touches[0].pageX;
startY = (slider.vertical) ? e.touches[0].pageX : e.touches[0].pageY;
slider.setTransition(0);
this.addEventListener('touchmove', onTouchMove, false);
this.addEventListener('touchend', onTouchEnd, false);
}
}
function onTouchMove(e) {
dx = (slider.vertical) ? startX - e.touches[0].pageY : startX - e.touches[0].pageX;
scrolling = (slider.vertical) ? (Math.abs(dx) < Math.abs(e.touches[0].pageX - startY)) : (Math.abs(dx) < Math.abs(e.touches[0].pageY - startY));
if (!scrolling) {
e.preventDefault();
if (slider.vars.animation == "slide" && slider.transitions) {
if (!slider.vars.animationLoop) {
dx = dx/((slider.currentSlide == 0 && dx < 0 || slider.currentSlide == slider.count - 1 && dx > 0) ? (Math.abs(dx)/cwidth+2) : 1);
}
slider.args[slider.prop] = (slider.vertical) ? "translate3d(0," + (-offset - dx) + "px,0)": "translate3d(" + (-offset - dx) + "px,0,0)";
slider.container.css(slider.args);
}
}
}
function onTouchEnd(e) {
slider.animating = false;
if (slider.animatingTo == slider.currentSlide && !scrolling && !(dx == null)) {
var target = (dx > 0) ? slider.getTarget('next') : slider.getTarget('prev');
if (slider.canAdvance(target) && Number(new Date()) - startT < 550 && Math.abs(dx) > 20 || Math.abs(dx) > cwidth/2) {
slider.flexAnimate(target, slider.vars.pauseOnAction);
} else {
slider.flexAnimate(slider.currentSlide, slider.vars.pauseOnAction);
}
}
//Finish the touch by undoing the touch session
this.removeEventListener('touchmove', onTouchMove, false);
this.removeEventListener('touchend', onTouchEnd, false);
startX = null;
startY = null;
dx = null;
offset = null;
}
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//FlexSlider: Resize Functions (If necessary)
if (slider.vars.animation.toLowerCase() == "slide") {
$(window).resize(function(){
if (!slider.animating) {
if (slider.vertical) {
slider.height(slider.slides.filter(':first').height());
slider.args[slider.prop] = (-1 * (slider.currentSlide + slider.cloneOffset))* slider.slides.filter(':first').height() + "px";
if (slider.transitions) {
slider.setTransition(0);
slider.args[slider.prop] = (slider.vertical) ? "translate3d(0," + slider.args[slider.prop] + ",0)" : "translate3d(" + slider.args[slider.prop] + ",0,0)";
}
slider.container.css(slider.args);
} else {
slider.newSlides.width(slider.width());
slider.args[slider.prop] = (-1 * (slider.currentSlide + slider.cloneOffset))* slider.width() + "px";
if (slider.transitions) {
slider.setTransition(0);
slider.args[slider.prop] = (slider.vertical) ? "translate3d(0," + slider.args[slider.prop] + ",0)" : "translate3d(" + slider.args[slider.prop] + ",0,0)";
}
slider.container.css(slider.args);
}
}
});
}
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
//FlexSlider: Destroy the slider entity
//Destory is not included in the minified version right now, but this is a working function for anyone who wants to include it.
//Simply bind the actions you need from this function into a function in the start() callback to the event of your chosing
/*
slider.destroy = function() {
slider.pause();
if (slider.controlNav && slider.vars.manualControls == "") slider.controlNav.closest('.flex-control-nav').remove();
if (slider.directionNav) slider.directionNav.closest('.flex-direction-nav').remove();
if (slider.vars.pausePlay) slider.pausePlay.closest('.flex-pauseplay').remove();
if (slider.vars.keyboardNav && $('ul.slides').length == 1) $(document).unbind('keyup', keyboardMove);
if (slider.vars.mousewheel) slider.unbind(slider.mousewheelEvent);
if (slider.transitions) slider.each(function(){this.removeEventListener('touchstart', onTouchStart, false);});
if (slider.vars.animation == "slide" && slider.vars.animationLoop) slider.newSlides.filter('.clone').remove();
if (slider.vertical) slider.height("auto");
slider.slides.hide();
slider.removeData('flexslider');
}
*/
//////////////////////////////////////////////////////////////////
//FlexSlider: start() Callback
slider.vars.start(slider);
}
//FlexSlider: Animation Actions
slider.flexAnimate = function(target, pause) {
if (!slider.animating) {
//Animating flag
slider.animating = true;
//FlexSlider: before() animation Callback
slider.animatingTo = target;
slider.vars.before(slider);
//Optional paramter to pause slider when making an anmiation call
if (pause) {
slider.pause();
}
//Update controlNav
if (slider.vars.controlNav) {
slider.controlNav.removeClass('active').eq(target).addClass('active');
}
//Is the slider at either end
slider.atEnd = (target == 0 || target == slider.count - 1) ? true : false;
if (!slider.vars.animationLoop && slider.vars.directionNav) {
if (target == 0) {
slider.directionNav.removeClass('disabled').filter('.prev').addClass('disabled');
} else if (target == slider.count - 1) {
slider.directionNav.removeClass('disabled').filter('.next').addClass('disabled');
} else {
slider.directionNav.removeClass('disabled');
}
}
if (!slider.vars.animationLoop && target == slider.count - 1) {
slider.pause();
//FlexSlider: end() of cycle Callback
slider.vars.end(slider);
}
if (slider.vars.animation.toLowerCase() == "slide") {
var dimension = (slider.vertical) ? slider.slides.filter(':first').height() : slider.slides.filter(':first').width();
if (slider.currentSlide == 0 && target == slider.count - 1 && slider.vars.animationLoop && slider.direction != "next") {
slider.slideString = "0px";
} else if (slider.currentSlide == slider.count - 1 && target == 0 && slider.vars.animationLoop && slider.direction != "prev") {
slider.slideString = (-1 * (slider.count + 1)) * dimension + "px";
} else {
slider.slideString = (-1 * (target + slider.cloneOffset)) * dimension + "px";
}
slider.args[slider.prop] = slider.slideString;
if (slider.transitions) {
slider.setTransition(slider.vars.animationDuration);
slider.args[slider.prop] = (slider.vertical) ? "translate3d(0," + slider.slideString + ",0)" : "translate3d(" + slider.slideString + ",0,0)";
slider.container.css(slider.args).one("webkitTransitionEnd transitionend", function(){
slider.wrapup(dimension);
});
} else {
slider.container.animate(slider.args, slider.vars.animationDuration, function(){
slider.wrapup(dimension);
});
}
} else { //Default to Fade
slider.slides.eq(slider.currentSlide).fadeOut(slider.vars.animationDuration);
slider.slides.eq(target).fadeIn(slider.vars.animationDuration, function() {
slider.wrapup();
});
}
}
}
//FlexSlider: Function to minify redundant animation actions
slider.wrapup = function(dimension) {
if (slider.vars.animation == "slide") {
//Jump the slider if necessary
if (slider.currentSlide == 0 && slider.animatingTo == slider.count - 1 && slider.vars.animationLoop) {
slider.args[slider.prop] = (-1 * slider.count) * dimension + "px";
if (slider.transitions) {
slider.setTransition(0);
slider.args[slider.prop] = (slider.vertical) ? "translate3d(0," + slider.args[slider.prop] + ",0)" : "translate3d(" + slider.args[slider.prop] + ",0,0)";
}
slider.container.css(slider.args);
} else if (slider.currentSlide == slider.count - 1 && slider.animatingTo == 0 && slider.vars.animationLoop) {
slider.args[slider.prop] = -1 * dimension + "px";
if (slider.transitions) {
slider.setTransition(0);
slider.args[slider.prop] = (slider.vertical) ? "translate3d(0," + slider.args[slider.prop] + ",0)" : "translate3d(" + slider.args[slider.prop] + ",0,0)";
}
slider.container.css(slider.args);
}
}
slider.animating = false;
slider.currentSlide = slider.animatingTo;
//FlexSlider: after() animation Callback
slider.vars.after(slider);
}
//FlexSlider: Automatic Slideshow
slider.animateSlides = function() {
if (!slider.animating) {
slider.flexAnimate(slider.getTarget("next"));
}
}
//FlexSlider: Automatic Slideshow Pause
slider.pause = function() {
clearInterval(slider.animatedSlides);
if (slider.vars.pausePlay) {
slider.pausePlay.removeClass('pause').addClass('play').text(slider.vars.playText);
}
}
//FlexSlider: Automatic Slideshow Start/Resume
slider.resume = function() {
slider.animatedSlides = setInterval(slider.animateSlides, slider.vars.slideshowSpeed);
if (slider.vars.pausePlay) {
slider.pausePlay.removeClass('play').addClass('pause').text(slider.vars.pauseText);
}
}
//FlexSlider: Helper function for non-looping sliders
slider.canAdvance = function(target) {
if (!slider.vars.animationLoop && slider.atEnd) {
if (slider.currentSlide == 0 && target == slider.count - 1 && slider.direction != "next") {
return false;
} else if (slider.currentSlide == slider.count - 1 && target == 0 && slider.direction == "next") {
return false;
} else {
return true;
}
} else {
return true;
}
}
//FlexSlider: Helper function to determine animation target
slider.getTarget = function(dir) {
slider.direction = dir;
if (dir == "next") {
return (slider.currentSlide == slider.count - 1) ? 0 : slider.currentSlide + 1;
} else {
return (slider.currentSlide == 0) ? slider.count - 1 : slider.currentSlide - 1;
}
}
//FlexSlider: Helper function to set CSS3 transitions
slider.setTransition = function(dur) {
slider.container.css({'-webkit-transition-duration': (dur/1000) + "s"});
}
//FlexSlider: Initialize
slider.init();
}
//FlexSlider: Default Settings
$.flexslider.defaults = {
animation: "fade", //String: Select your animation type, "fade" or "slide"
slideDirection: "horizontal", //String: Select the sliding direction, "horizontal" or "vertical"
slideshow: true, //Boolean: Animate slider automatically
slideshowSpeed: 6000, //Integer: Set the speed of the slideshow cycling, in milliseconds
animationDuration: 600, //Integer: Set the speed of animations, in milliseconds
directionNav: true, //Boolean: Create navigation for previous/next navigation? (true/false)
controlNav: true, //Boolean: Create navigation for paging control of each clide? Note: Leave true for manualControls usage
keyboardNav: true, //Boolean: Allow slider navigating via keyboard left/right keys
mousewheel: false, //Boolean: Allow slider navigating via mousewheel
prevText: "Previous", //String: Set the text for the "previous" directionNav item
nextText: "Next", //String: Set the text for the "next" directionNav item
pausePlay: false, //Boolean: Create pause/play dynamic element
pauseText: 'Pause', //String: Set the text for the "pause" pausePlay item
playText: 'Play', //String: Set the text for the "play" pausePlay item
randomize: false, //Boolean: Randomize slide order
slideToStart: 0, //Integer: The slide that the slider should start on. Array notation (0 = first slide)
animationLoop: true, //Boolean: Should the animation loop? If false, directionNav will received "disable" classes at either end
pauseOnAction: false, //Boolean: Pause the slideshow when interacting with control elements, highly recommended.
pauseOnHover: false, //Boolean: Pause the slideshow when hovering over slider, then resume when no longer hovering
controlsContainer: "", //Selector: Declare which container the navigation elements should be appended too. Default container is the flexSlider element. Example use would be ".flexslider-container", "#container", etc. If the given element is not found, the default action will be taken.
manualControls: "", //Selector: Declare custom control navigation. Example would be ".flex-control-nav li" or "#tabs-nav li img", etc. The number of elements in your controlNav should match the number of slides/tabs.
start: function(){}, //Callback: function(slider) - Fires when the slider loads the first slide
before: function(){}, //Callback: function(slider) - Fires asynchronously with each slider animation
after: function(){}, //Callback: function(slider) - Fires after each slider animation completes
end: function(){} //Callback: function(slider) - Fires when the slider reaches the last slide (asynchronous)
}
//FlexSlider: Plugin Function
$.fn.flexslider = function(options) {
return this.each(function() {
if ($(this).find('.slides li').length == 1) {
$(this).find('.slides li').fadeIn(400);
}
else if ($(this).data('flexslider') != true) {
new $.flexslider($(this), options);
}
});
}
})(jQuery);
As always, thank you.
do this instead
var result = document.getElementById("id-height").offsetHeight;
alert(result + " px");
pure js raw solution.
jquery
var result = $("#id-height").height();
alert(result + " px");

Touch event handle with mousedown, mousemove and mouseup in standard javascript not jquery

Any body please tell me how can I create a touch event handle with 3 event available in javascript are mousedown, mousemove and mouseup?
Any idea is appreciated!
I have an idea for my own question and I'm using this to moving my slideshow like this:
function Dragging() {
var isDragging = false;
var isStartDragging = false;
var isEndDragging = true;
var startPoint = 0;
$('.Content-Page-List').mousedown(function (e) {
e = e || event;
if (!isStartDragging && !isDragging && isEndDragging) { isStartDragging = true; isEndDragging = false; startPoint = e.pageX; }
else { isStartDragging = isDragging = false; }
});
$('.Content-Page-List').mousemove(function () {
if (isStartDragging && !isEndDragging) { isDragging = true;}
else { return; }
});
$('.Content-Page-List').mouseup(function (e) {
e = e || event;
var leftVal = $(this).position().left;
if (isDragging && !isSlideMoving) {
var oldSlide = slide;
/* Slide move from left to right */
if (startPoint < e.pageX) {
if (leftVal == 0) return;
isSlideMoving = true;
$('.Content-Page-List').animate({ left: (leftVal + 1200) + 'px' }, 'slow', function () {
slide = parseInt(slide - 1);
contentHeight = $('.Content-Page-List').children('ul').children('li').eq(slide).height();
$('#page' + slide).parent().parent().css('background', 'rgba(243, 0, 0, 0.6)');
$('#Content-Page-List-Wrapper').css('height', contentHeight + 'px');
isStartDragging = isDragging = false;
isEndDragging = true;
isSlideMoving = false;
});
}
/*Slide move from right to left */
else {
if (leftVal == -((numOfLi * 1200) - 1200) || numOfLi == 1) return;
isSlideMoving = true;
$('.Content-Page-List').animate({ left: (leftVal - 1200) + 'px' }, 'slow', function () {
slide = parseInt(slide + 1);
contentHeight = $('.Content-Page-List').children('ul').children('li').eq(slide).height();
$('#page' + slide).parent().parent().css('background', 'rgba(243, 0, 0, 0.6)');
$('#Content-Page-List-Wrapper').css('height', contentHeight + 'px');
isStartDragging = isDragging = false;
isEndDragging = true;
isSlideMoving = false;
});
}
$('#page' + oldSlide).parent().parent().css('background', '#f4f4f4');
}
else { isStartDragging = false; isEndDragging = true; }
});

adding autoplay to jquery.roundabout

I have a site I am working on that uses the roundabout from fredhq.com and I would like to make it so it auto plays, I have had a look on their website and can not work out where I need to add the relevant auto play code!
Here is the jquery.roundabout.js code:
// creates a default shape to be used for pathing
jQuery.extend({
roundabout_shape: {
def: 'lazySusan',
lazySusan: function(r, a, t) {
return {
x: Math.sin(r + a),
y: (Math.sin(r + 3*Math.PI/2 + a) / 8) * t,
z: (Math.cos(r + a) + 1) / 2,
scale: (Math.sin(r + Math.PI/2 + a) / 2) + 0.5
};
}
}
});
jQuery.fn.roundabout = function() {
var options = (typeof arguments[0] != 'object') ? {} : arguments[0];
// set options and fill in defaults
options = {
bearing: (typeof options.bearing == 'undefined') ? 0.0 : jQuery.roundabout_toFloat(options.bearing % 360.0),
tilt: (typeof options.tilt == 'undefined') ? 0.0 : jQuery.roundabout_toFloat(options.tilt),
minZ: (typeof options.minZ == 'undefined') ? 100 : parseInt(options.minZ, 10),
maxZ: (typeof options.maxZ == 'undefined') ? 400 : parseInt(options.maxZ, 10),
minOpacity: (typeof options.minOpacity == 'undefined') ? 0.40 : jQuery.roundabout_toFloat(options.minOpacity),
maxOpacity: (typeof options.maxOpacity == 'undefined') ? 1.00 : jQuery.roundabout_toFloat(options.maxOpacity),
minScale: (typeof options.minScale == 'undefined') ? 0.40 : jQuery.roundabout_toFloat(options.minScale),
maxScale: (typeof options.maxScale == 'undefined') ? 1.00 : jQuery.roundabout_toFloat(options.maxScale),
duration: (typeof options.duration == 'undefined') ? 600 : parseInt(options.duration, 10),
btnNext: options.btnNext || null,
btnPrev: options.btnPrev || null,
easing: options.easing || 'swing',
clickToFocus: (options.clickToFocus !== false),
focusBearing: (typeof options.focusBearing == 'undefined') ? 0.0 : jQuery.roundabout_toFloat(options.focusBearing % 360.0),
shape: options.shape || 'lazySusan',
debug: options.debug || false,
childSelector: options.childSelector || 'li',
startingChild: (typeof options.startingChild == 'undefined') ? null : parseInt(options.startingChild, 10),
reflect: (typeof options.reflect == 'undefined' || options.reflect === false) ? false : true
};
// assign things
this.each(function(i) {
var ref = jQuery(this);
var period = jQuery.roundabout_toFloat(360.0 / ref.children(options.childSelector).length);
var startingBearing = (options.startingChild === null) ? options.bearing : options.startingChild * period;
// set starting styles
ref
.addClass('roundabout-holder')
.css('padding', 0)
.css('position', 'relative')
.css('z-index', options.minZ);
// set starting options
ref.data('roundabout', {
'bearing': startingBearing,
'tilt': options.tilt,
'minZ': options.minZ,
'maxZ': options.maxZ,
'minOpacity': options.minOpacity,
'maxOpacity': options.maxOpacity,
'minScale': options.minScale,
'maxScale': options.maxScale,
'duration': options.duration,
'easing': options.easing,
'clickToFocus': options.clickToFocus,
'focusBearing': options.focusBearing,
'animating': 0,
'childInFocus': -1,
'shape': options.shape,
'period': period,
'debug': options.debug,
'childSelector': options.childSelector,
'reflect': options.reflect
});
// bind click events
if (options.clickToFocus === true) {
ref.children(options.childSelector).each(function(i) {
jQuery(this).click(function(e) {
var degrees = (options.reflect === true) ? 360.0 - (period * i) : period * i;
degrees = jQuery.roundabout_toFloat(degrees);
if (!jQuery.roundabout_isInFocus(ref, degrees)) {
e.preventDefault();
if (ref.data('roundabout').animating === 0) {
ref.roundabout_animateAngleToFocus(degrees);
}
return false;
}
});
});
}
// bind next buttons
if (options.btnNext) {
jQuery(options.btnNext).bind('click.roundabout', function(e) {
e.preventDefault();
if (ref.data('roundabout').animating === 0) {
ref.roundabout_animateToNextChild();
}
return false;
});
}
// bind previous buttons
if (options.btnPrev) {
jQuery(options.btnPrev).bind('click.roundabout', function(e) {
e.preventDefault();
if (ref.data('roundabout').animating === 0) {
ref.roundabout_animateToPreviousChild();
}
return false;
});
}
});
// start children
this.roundabout_startChildren();
// callback once ready
if (typeof arguments[1] === 'function') {
var callback = arguments[1], ref = this;
setTimeout(function() { callback(ref); }, 0);
}
return this;
};
jQuery.fn.roundabout_startChildren = function() {
this.each(function(i) {
var ref = jQuery(this);
var data = ref.data('roundabout');
var children = ref.children(data.childSelector);
children.each(function(i) {
var degrees = (data.reflect === true) ? 360.0 - (data.period * i) : data.period * i;
// apply classes and css first
jQuery(this)
.addClass('roundabout-moveable-item')
.css('position', 'absolute');
// then measure
jQuery(this).data('roundabout', {
'startWidth': jQuery(this).width(),
'startHeight': jQuery(this).height(),
'startFontSize': parseInt(jQuery(this).css('font-size'), 10),
'degrees': degrees
});
});
ref.roundabout_updateChildPositions();
});
return this;
};
jQuery.fn.roundabout_setTilt = function(newTilt) {
this.each(function(i) {
jQuery(this).data('roundabout').tilt = newTilt;
jQuery(this).roundabout_updateChildPositions();
});
if (typeof arguments[1] === 'function') {
var callback = arguments[1], ref = this;
setTimeout(function() { callback(ref); }, 0);
}
return this;
};
jQuery.fn.roundabout_setBearing = function(newBearing) {
this.each(function(i) {
jQuery(this).data('roundabout').bearing = jQuery.roundabout_toFloat(newBearing % 360, 2);
jQuery(this).roundabout_updateChildPositions();
});
if (typeof arguments[1] === 'function') {
var callback = arguments[1], ref = this;
setTimeout(function() { callback(ref); }, 0);
}
return this;
};
jQuery.fn.roundabout_adjustBearing = function(delta) {
delta = jQuery.roundabout_toFloat(delta);
if (delta !== 0) {
this.each(function(i) {
jQuery(this).data('roundabout').bearing = jQuery.roundabout_getBearing(jQuery(this)) + delta;
jQuery(this).roundabout_updateChildPositions();
});
}
if (typeof arguments[1] === 'function') {
var callback = arguments[1], ref = this;
setTimeout(function() { callback(ref); }, 0);
}
return this;
};
jQuery.fn.roundabout_adjustTilt = function(delta) {
delta = jQuery.roundabout_toFloat(delta);
if (delta !== 0) {
this.each(function(i) {
jQuery(this).data('roundabout').tilt = jQuery.roundabout_toFloat(jQuery(this).roundabout_get('tilt') + delta);
jQuery(this).roundabout_updateChildPositions();
});
}
if (typeof arguments[1] === 'function') {
var callback = arguments[1], ref = this;
setTimeout(function() { callback(ref); }, 0);
}
return this;
};
jQuery.fn.roundabout_animateToBearing = function(bearing) {
bearing = jQuery.roundabout_toFloat(bearing);
var currentTime = new Date();
var duration = (typeof arguments[1] == 'undefined') ? null : arguments[1];
var easingType = (typeof arguments[2] == 'undefined') ? null : arguments[2];
var passedData = (typeof arguments[3] !== 'object') ? null : arguments[3];
this.each(function(i) {
var ref = jQuery(this), data = ref.data('roundabout'), timer, easingFn, newBearing;
var thisDuration = (duration === null) ? data.duration : duration;
var thisEasingType = (easingType !== null) ? easingType : data.easing || 'swing';
if (passedData === null) {
passedData = {
timerStart: currentTime,
start: jQuery.roundabout_getBearing(ref),
totalTime: thisDuration
};
}
timer = currentTime - passedData.timerStart;
if (timer < thisDuration) {
data.animating = 1;
if (typeof jQuery.easing.def == 'string') {
easingFn = jQuery.easing[thisEasingType] || jQuery.easing[jQuery.easing.def];
newBearing = easingFn(null, timer, passedData.start, bearing - passedData.start, passedData.totalTime);
} else {
newBearing = jQuery.easing[thisEasingType]((timer / passedData.totalTime), timer, passedData.start, bearing - passedData.start, passedData.totalTime);
}
ref.roundabout_setBearing(newBearing, function() { ref.roundabout_animateToBearing(bearing, thisDuration, thisEasingType, passedData); });
} else {
bearing = (bearing < 0) ? bearing + 360 : bearing % 360;
data.animating = 0;
ref.roundabout_setBearing(bearing);
}
});
return this;
};
jQuery.fn.roundabout_animateToDelta = function(delta) {
var duration = arguments[1], easing = arguments[2];
this.each(function(i) {
delta = jQuery.roundabout_getBearing(jQuery(this)) + jQuery.roundabout_toFloat(delta);
jQuery(this).roundabout_animateToBearing(delta, duration, easing);
});
return this;
};
jQuery.fn.roundabout_animateToChild = function(childPos) {
var duration = arguments[1], easing = arguments[2];
this.each(function(i) {
var ref = jQuery(this), data = ref.data('roundabout');
if (data.childInFocus !== childPos && data.animating === 0) {
var child = jQuery(ref.children(data.childSelector)[childPos]);
ref.roundabout_animateAngleToFocus(child.data('roundabout').degrees, duration, easing);
}
});
return this;
};
jQuery.fn.roundabout_animateToNearbyChild = function(passedArgs, which) {
var duration = passedArgs[0], easing = passedArgs[1];
this.each(function(i) {
var data = jQuery(this).data('roundabout');
var bearing = jQuery.roundabout_toFloat(360.0 - jQuery.roundabout_getBearing(jQuery(this)));
var period = data.period, j = 0, range;
var reflect = data.reflect;
var length = jQuery(this).children(data.childSelector).length;
bearing = (reflect === true) ? bearing % 360.0 : bearing;
if (data.animating === 0) {
// if we're not reflecting and we're moving to next or
// we are reflecting and we're moving previous
if ((reflect === false && which === 'next') || (reflect === true && which !== 'next')) {
bearing = (bearing === 0) ? 360 : bearing;
// counterclockwise
while (true && j < length) {
range = { lower: jQuery.roundabout_toFloat(period * j), upper: jQuery.roundabout_toFloat(period * (j + 1)) };
range.upper = (j == length - 1) ? 360.0 : range.upper; // adjust for javascript being bad at floats
if (bearing <= range.upper && bearing > range.lower) {
jQuery(this).roundabout_animateToDelta(bearing - range.lower, duration, easing);
break;
}
j++;
}
} else {
// clockwise
while (true) {
range = { lower: jQuery.roundabout_toFloat(period * j), upper: jQuery.roundabout_toFloat(period * (j + 1)) };
range.upper = (j == length - 1) ? 360.0 : range.upper; // adjust for javascript being bad at floats
if (bearing >= range.lower && bearing < range.upper) {
jQuery(this).roundabout_animateToDelta(bearing - range.upper, duration, easing);
break;
}
j++;
}
}
}
});
return this;
};
jQuery.fn.roundabout_animateToNextChild = function() {
return this.roundabout_animateToNearbyChild(arguments, 'next');
};
jQuery.fn.roundabout_animateToPreviousChild = function() {
return this.roundabout_animateToNearbyChild(arguments, 'previous');
};
// moves a given angle to the focus by the shortest means possible
jQuery.fn.roundabout_animateAngleToFocus = function(target) {
var duration = arguments[1], easing = arguments[2];
this.each(function(i) {
var delta = jQuery.roundabout_getBearing(jQuery(this)) - target;
delta = (Math.abs(360.0 - delta) < Math.abs(0.0 - delta)) ? 360.0 - delta : 0.0 - delta;
delta = (delta > 180) ? -(360.0 - delta) : delta;
if (delta !== 0) {
jQuery(this).roundabout_animateToDelta(delta, duration, easing);
}
});
return this;
};
jQuery.fn.roundabout_updateChildPositions = function() {
this.each(function(i) {
var ref = jQuery(this), data = ref.data('roundabout');
var inFocus = -1;
var info = {
bearing: jQuery.roundabout_getBearing(ref),
tilt: data.tilt,
stage: { width: Math.floor(ref.width() * 0.9), height: Math.floor(ref.height() * 0.9) },
animating: data.animating,
inFocus: data.childInFocus,
focusBearingRad: jQuery.roundabout_degToRad(data.focusBearing),
shape: jQuery.roundabout_shape[data.shape] || jQuery.roundabout_shape[jQuery.roundabout_shape.def]
};
info.midStage = { width: info.stage.width / 2, height: info.stage.height / 2 };
info.nudge = { width: info.midStage.width + info.stage.width * 0.05, height: info.midStage.height + info.stage.height * 0.05 };
info.zValues = { min: data.minZ, max: data.maxZ, diff: data.maxZ - data.minZ };
info.opacity = { min: data.minOpacity, max: data.maxOpacity, diff: data.maxOpacity - data.minOpacity };
info.scale = { min: data.minScale, max: data.maxScale, diff: data.maxScale - data.minScale };
// update child positions
ref.children(data.childSelector).each(function(i) {
if (jQuery.roundabout_updateChildPosition(jQuery(this), ref, info, i) && info.animating === 0) {
inFocus = i;
jQuery(this).addClass('roundabout-in-focus');
} else {
jQuery(this).removeClass('roundabout-in-focus');
}
});
// update status of who is in focus
if (inFocus !== info.inFocus) {
jQuery.roundabout_triggerEvent(ref, info.inFocus, 'blur');
if (inFocus !== -1) {
jQuery.roundabout_triggerEvent(ref, inFocus, 'focus');
}
data.childInFocus = inFocus;
}
});
return this;
};
//----------------
jQuery.roundabout_getBearing = function(el) {
return jQuery.roundabout_toFloat(el.data('roundabout').bearing) % 360;
};
jQuery.roundabout_degToRad = function(degrees) {
return (degrees % 360.0) * Math.PI / 180.0;
};
jQuery.roundabout_isInFocus = function(el, target) {
return (jQuery.roundabout_getBearing(el) % 360 === (target % 360));
};
jQuery.roundabout_triggerEvent = function(el, child, eventType) {
return (child < 0) ? this : jQuery(el.children(el.data('roundabout').childSelector)[child]).trigger(eventType);
};
jQuery.roundabout_toFloat = function(number) {
number = Math.round(parseFloat(number) * 1000) / 1000;
return parseFloat(number.toFixed(2));
};
jQuery.roundabout_updateChildPosition = function(child, container, info, childPos) {
var ref = jQuery(child), data = ref.data('roundabout'), out = [];
var rad = jQuery.roundabout_degToRad((360.0 - ref.data('roundabout').degrees) + info.bearing);
// adjust radians to be between 0 and Math.PI * 2
while (rad < 0) {
rad = rad + Math.PI * 2;
}
while (rad > Math.PI * 2) {
rad = rad - Math.PI * 2;
}
var factors = info.shape(rad, info.focusBearingRad, info.tilt); // obj with x, y, z, and scale values
// correct
factors.scale = (factors.scale > 1) ? 1 : factors.scale;
factors.adjustedScale = (info.scale.min + (info.scale.diff * factors.scale)).toFixed(4);
factors.width = (factors.adjustedScale * data.startWidth).toFixed(4);
factors.height = (factors.adjustedScale * data.startHeight).toFixed(4);
// alter item
ref
.css('left', ((factors.x * info.midStage.width + info.nudge.width) - factors.width / 2.0).toFixed(1) + 'px')
.css('top', ((factors.y * info.midStage.height + info.nudge.height) - factors.height / 2.0).toFixed(1) + 'px')
.css('width', factors.width + 'px')
.css('height', factors.height + 'px')
.css('opacity', (info.opacity.min + (info.opacity.diff * factors.scale)).toFixed(2))
.css('z-index', Math.round(info.zValues.min + (info.zValues.diff * factors.z)))
.css('font-size', (factors.adjustedScale * data.startFontSize).toFixed(2) + 'px')
.attr('current-scale', factors.adjustedScale);
if (container.data('roundabout').debug === true) {
out.push('<div style="font-weight: normal; font-size: 10px; padding: 2px; width: ' + ref.css('width') + '; background-color: #ffc;">');
out.push('<strong style="font-size: 12px; white-space: nowrap;">Child ' + childPos + '</strong><br />');
out.push('<strong>left:</strong> ' + ref.css('left') + '<br /><strong>top:</strong> ' + ref.css('top') + '<br />');
out.push('<strong>width:</strong> ' + ref.css('width') + '<br /><strong>opacity:</strong> ' + ref.css('opacity') + '<br />');
out.push('<strong>z-index:</strong> ' + ref.css('z-index') + '<br /><strong>font-size:</strong> ' + ref.css('font-size') + '<br />');
out.push('<strong>scale:</strong> ' + ref.attr('current-scale'));
out.push('</div>');
ref.html(out.join(''));
}
return jQuery.roundabout_isInFocus(container, ref.data('roundabout').degrees);
};
Many thanks in advance for any help and advice.
Phil
The source you posted doesn't seem to be the latest version of Roundabout.
I just tried with the latest version, and it works perfectly:
$(document).ready(function() {
$('ul').roundabout({
autoplay: true,
autoplayDuration: 1000,
autoplayPauseOnHover: true
});
});
See http://jsfiddle.net/SfAuF/ for an example.
Download the latest version from GitHub.

Javascript problems with nivo slider

I can't figure out for the life of me what is causing these two errors, any help would be appreciated!
Uncaught TypeError: Object #<Object> has no method 'live'
$('a.nivo-prevNav', slider).live('click', function(){
Uncaught TypeError: Object #<Object> has no method 'live'
if(vars.running) return false;
clearInterval(timer);
timer = '';
vars.currentSlide -= 2;
nivoRun(slider, kids, settings, 'prev');
});
`Uncaught TypeError: Undefined is not a function (repeated 20 times)`
var timer = 0;
if(!settings.manualAdvance && kids.length > 1){
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
Uncaught TypeError: undefined is not a function (repeated 13 times)
}
The js file
/*
* jQuery Nivo Slider v2.6
* http://nivo.dev7studios.com
*
* Copyright 2011, Gilbert Pellegrom
* Free to use and abuse under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* March 2010
*/
(function($) {
var NivoSlider = function(element, options){
//Defaults are below
var settings = $.extend({}, $.fn.nivoSlider.defaults, options);
//Useful variables. Play carefully.
var vars = {
currentSlide: 0,
currentImage: '',
totalSlides: 0,
randAnim: '',
running: false,
paused: false,
stop: false
};
//Get this slider
var slider = $(element);
slider.data('nivo:vars', vars);
slider.css('position','relative');
slider.addClass('nivoSlider');
//Find our slider children
var kids = slider.children();
kids.each(function() {
var child = $(this);
var link = '';
if(!child.is('img')){
if(child.is('a')){
child.addClass('nivo-imageLink');
link = child;
}
child = child.find('img:first');
}
//Get img width & height
var childWidth = child.width();
if(childWidth == 0) childWidth = child.attr('width');
var childHeight = child.height();
if(childHeight == 0) childHeight = child.attr('height');
//Resize the slider
if(childWidth > slider.width()){
slider.width(childWidth);
}
if(childHeight > slider.height()){
slider.height(childHeight);
}
if(link != ''){
link.css('display','none');
}
child.css('display','none');
vars.totalSlides++;
});
//Set startSlide
if(settings.startSlide > 0){
if(settings.startSlide >= vars.totalSlides) settings.startSlide = vars.totalSlides - 1;
vars.currentSlide = settings.startSlide;
}
//Get initial image
if($(kids[vars.currentSlide]).is('img')){
vars.currentImage = $(kids[vars.currentSlide]);
} else {
vars.currentImage = $(kids[vars.currentSlide]).find('img:first');
}
//Show initial link
if($(kids[vars.currentSlide]).is('a')){
$(kids[vars.currentSlide]).css('display','block');
}
//Set first background
slider.css('background','url("'+ vars.currentImage.attr('src') +'") no-repeat');
//Create caption
slider.append(
$('<div class="nivo-caption"><p></p></div>').css({ display:'block', opacity:settings.captionOpacity })
);
// Process caption function
var processCaption = function(settings){
var nivoCaption = $('.nivo-caption', slider);
if(vars.currentImage.attr('title') != '' && vars.currentImage.attr('title') != undefined){
var title = vars.currentImage.attr('title');
if(title.substr(0,1) == '#') title = $(title).html();
if(nivoCaption.css('display') == 'block'){
nivoCaption.find('p').fadeOut(settings.animSpeed, function(){
$(this).html(title);
$(this).fadeIn(settings.animSpeed);
});
} else {
nivoCaption.find('p').html(title);
}
nivoCaption.fadeIn(settings.animSpeed);
} else {
nivoCaption.fadeOut(settings.animSpeed);
}
}
//Process initial caption
processCaption(settings);
//In the words of Super Mario "let's a go!"
var timer = 0;
if(!settings.manualAdvance && kids.length > 1){
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
}
//Add Direction nav
if(settings.directionNav){
slider.append('<div class="nivo-directionNav"><a class="nivo-prevNav">'+ settings.prevText +'</a><a class="nivo-nextNav">'+ settings.nextText +'</a></div>');
//Hide Direction nav
if(settings.directionNavHide){
$('.nivo-directionNav', slider).hide();
slider.hover(function(){
$('.nivo-directionNav', slider).show();
}, function(){
$('.nivo-directionNav', slider).hide();
});
}
$('a.nivo-prevNav', slider).live('click', function(){
if(vars.running) return false;
clearInterval(timer);
timer = '';
vars.currentSlide -= 2;
nivoRun(slider, kids, settings, 'prev');
});
$('a.nivo-nextNav', slider).live('click', function(){
if(vars.running) return false;
clearInterval(timer);
timer = '';
nivoRun(slider, kids, settings, 'next');
});
}
//Add Control nav
if(settings.controlNav){
var nivoControl = $('<div class="nivo-controlNav"></div>');
slider.append(nivoControl);
for(var i = 0; i < kids.length; i++){
if(settings.controlNavThumbs){
var child = kids.eq(i);
if(!child.is('img')){
child = child.find('img:first');
}
if (settings.controlNavThumbsFromRel) {
nivoControl.append('<a class="nivo-control" rel="'+ i +'"><img src="'+ child.attr('rel') + '" alt="" /></a>');
} else {
nivoControl.append('<a class="nivo-control" rel="'+ i +'"><img src="'+ child.attr('src').replace(settings.controlNavThumbsSearch, settings.controlNavThumbsReplace) +'" alt="" /></a>');
}
} else {
nivoControl.append('<a class="nivo-control" rel="'+ i +'">'+ (i + 1) +'</a>');
}
}
//Set initial active link
$('.nivo-controlNav a:eq('+ vars.currentSlide +')', slider).addClass('active');
$('.nivo-controlNav a', slider).live('click', function(){
if(vars.running) return false;
if($(this).hasClass('active')) return false;
clearInterval(timer);
timer = '';
slider.css('background','url("'+ vars.currentImage.attr('src') +'") no-repeat');
vars.currentSlide = $(this).attr('rel') - 1;
nivoRun(slider, kids, settings, 'control');
});
}
//Keyboard Navigation
if(settings.keyboardNav){
$(window).keypress(function(event){
//Left
if(event.keyCode == '37'){
if(vars.running) return false;
clearInterval(timer);
timer = '';
vars.currentSlide-=2;
nivoRun(slider, kids, settings, 'prev');
}
//Right
if(event.keyCode == '39'){
if(vars.running) return false;
clearInterval(timer);
timer = '';
nivoRun(slider, kids, settings, 'next');
}
});
}
//For pauseOnHover setting
if(settings.pauseOnHover){
slider.hover(function(){
vars.paused = true;
clearInterval(timer);
timer = '';
}, function(){
vars.paused = false;
//Restart the timer
if(timer == '' && !settings.manualAdvance){
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
}
});
}
//Event when Animation finishes
slider.bind('nivo:animFinished', function(){
vars.running = false;
//Hide child links
$(kids).each(function(){
if($(this).is('a')){
$(this).css('display','none');
}
});
//Show current link
if($(kids[vars.currentSlide]).is('a')){
$(kids[vars.currentSlide]).css('display','block');
}
//Restart the timer
if(timer == '' && !vars.paused && !settings.manualAdvance){
timer = setInterval(function(){ nivoRun(slider, kids, settings, false); }, settings.pauseTime);
}
//Trigger the afterChange callback
settings.afterChange.call(this);
});
// Add slices for slice animations
var createSlices = function(slider, settings, vars){
for(var i = 0; i < settings.slices; i++){
var sliceWidth = Math.round(slider.width()/settings.slices);
if(i == settings.slices-1){
slider.append(
$('<div class="nivo-slice"></div>').css({
left:(sliceWidth*i)+'px', width:(slider.width()-(sliceWidth*i))+'px',
height:'0px',
opacity:'0',
background: 'url("'+ vars.currentImage.attr('src') +'") no-repeat -'+ ((sliceWidth + (i * sliceWidth)) - sliceWidth) +'px 0%'
})
);
} else {
slider.append(
$('<div class="nivo-slice"></div>').css({
left:(sliceWidth*i)+'px', width:sliceWidth+'px',
height:'0px',
opacity:'0',
background: 'url("'+ vars.currentImage.attr('src') +'") no-repeat -'+ ((sliceWidth + (i * sliceWidth)) - sliceWidth) +'px 0%'
})
);
}
}
}
// Add boxes for box animations
var createBoxes = function(slider, settings, vars){
var boxWidth = Math.round(slider.width()/settings.boxCols);
var boxHeight = Math.round(slider.height()/settings.boxRows);
for(var rows = 0; rows < settings.boxRows; rows++){
for(var cols = 0; cols < settings.boxCols; cols++){
if(cols == settings.boxCols-1){
slider.append(
$('<div class="nivo-box"></div>').css({
opacity:0,
left:(boxWidth*cols)+'px',
top:(boxHeight*rows)+'px',
width:(slider.width()-(boxWidth*cols))+'px',
height:boxHeight+'px',
background: 'url("'+ vars.currentImage.attr('src') +'") no-repeat -'+ ((boxWidth + (cols * boxWidth)) - boxWidth) +'px -'+ ((boxHeight + (rows * boxHeight)) - boxHeight) +'px'
})
);
} else {
slider.append(
$('<div class="nivo-box"></div>').css({
opacity:0,
left:(boxWidth*cols)+'px',
top:(boxHeight*rows)+'px',
width:boxWidth+'px',
height:boxHeight+'px',
background: 'url("'+ vars.currentImage.attr('src') +'") no-repeat -'+ ((boxWidth + (cols * boxWidth)) - boxWidth) +'px -'+ ((boxHeight + (rows * boxHeight)) - boxHeight) +'px'
})
);
}
}
}
}
// Private run method
var nivoRun = function(slider, kids, settings, nudge){
//Get our vars
var vars = slider.data('nivo:vars');
//Trigger the lastSlide callback
if(vars && (vars.currentSlide == vars.totalSlides - 1)){
settings.lastSlide.call(this);
}
// Stop
if((!vars || vars.stop) && !nudge) return false;
//Trigger the beforeChange callback
settings.beforeChange.call(this);
//Set current background before change
if(!nudge){
slider.css('background','url("'+ vars.currentImage.attr('src') +'") no-repeat');
} else {
if(nudge == 'prev'){
slider.css('background','url("'+ vars.currentImage.attr('src') +'") no-repeat');
}
if(nudge == 'next'){
slider.css('background','url("'+ vars.currentImage.attr('src') +'") no-repeat');
}
}
vars.currentSlide++;
//Trigger the slideshowEnd callback
if(vars.currentSlide == vars.totalSlides){
vars.currentSlide = 0;
settings.slideshowEnd.call(this);
}
if(vars.currentSlide < 0) vars.currentSlide = (vars.totalSlides - 1);
//Set vars.currentImage
if($(kids[vars.currentSlide]).is('img')){
vars.currentImage = $(kids[vars.currentSlide]);
} else {
vars.currentImage = $(kids[vars.currentSlide]).find('img:first');
}
//Set active links
if(settings.controlNav){
$('.nivo-controlNav a', slider).removeClass('active');
$('.nivo-controlNav a:eq('+ vars.currentSlide +')', slider).addClass('active');
}
//Process caption
processCaption(settings);
// Remove any slices from last transition
$('.nivo-slice', slider).remove();
// Remove any boxes from last transition
$('.nivo-box', slider).remove();
if(settings.effect == 'random'){
var anims = new Array('sliceDownRight','sliceDownLeft','sliceUpRight','sliceUpLeft','sliceUpDown','sliceUpDownLeft','fold','fade',
'boxRandom','boxRain','boxRainReverse','boxRainGrow','boxRainGrowReverse');
vars.randAnim = anims[Math.floor(Math.random()*(anims.length + 1))];
if(vars.randAnim == undefined) vars.randAnim = 'fade';
}
//Run random effect from specified set (eg: effect:'fold,fade')
if(settings.effect.indexOf(',') != -1){
var anims = settings.effect.split(',');
vars.randAnim = anims[Math.floor(Math.random()*(anims.length))];
if(vars.randAnim == undefined) vars.randAnim = 'fade';
}
//Run effects
vars.running = true;
if(settings.effect == 'sliceDown' || settings.effect == 'sliceDownRight' || vars.randAnim == 'sliceDownRight' ||
settings.effect == 'sliceDownLeft' || vars.randAnim == 'sliceDownLeft'){
createSlices(slider, settings, vars);
var timeBuff = 0;
var i = 0;
var slices = $('.nivo-slice', slider);
if(settings.effect == 'sliceDownLeft' || vars.randAnim == 'sliceDownLeft') slices = $('.nivo-slice', slider)._reverse();
slices.each(function(){
var slice = $(this);
slice.css({ 'top': '0px' });
if(i == settings.slices-1){
setTimeout(function(){
slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
}
else if(settings.effect == 'sliceUp' || settings.effect == 'sliceUpRight' || vars.randAnim == 'sliceUpRight' ||
settings.effect == 'sliceUpLeft' || vars.randAnim == 'sliceUpLeft'){
createSlices(slider, settings, vars);
var timeBuff = 0;
var i = 0;
var slices = $('.nivo-slice', slider);
if(settings.effect == 'sliceUpLeft' || vars.randAnim == 'sliceUpLeft') slices = $('.nivo-slice', slider)._reverse();
slices.each(function(){
var slice = $(this);
slice.css({ 'bottom': '0px' });
if(i == settings.slices-1){
setTimeout(function(){
slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
}
else if(settings.effect == 'sliceUpDown' || settings.effect == 'sliceUpDownRight' || vars.randAnim == 'sliceUpDown' ||
settings.effect == 'sliceUpDownLeft' || vars.randAnim == 'sliceUpDownLeft'){
createSlices(slider, settings, vars);
var timeBuff = 0;
var i = 0;
var v = 0;
var slices = $('.nivo-slice', slider);
if(settings.effect == 'sliceUpDownLeft' || vars.randAnim == 'sliceUpDownLeft') slices = $('.nivo-slice', slider)._reverse();
slices.each(function(){
var slice = $(this);
if(i == 0){
slice.css('top','0px');
i++;
} else {
slice.css('bottom','0px');
i = 0;
}
if(v == settings.slices-1){
setTimeout(function(){
slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
slice.animate({ height:'100%', opacity:'1.0' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
v++;
});
}
else if(settings.effect == 'fold' || vars.randAnim == 'fold'){
createSlices(slider, settings, vars);
var timeBuff = 0;
var i = 0;
$('.nivo-slice', slider).each(function(){
var slice = $(this);
var origWidth = slice.width();
slice.css({ top:'0px', height:'100%', width:'0px' });
if(i == settings.slices-1){
setTimeout(function(){
slice.animate({ width:origWidth, opacity:'1.0' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
slice.animate({ width:origWidth, opacity:'1.0' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 50;
i++;
});
}
else if(settings.effect == 'fade' || vars.randAnim == 'fade'){
createSlices(slider, settings, vars);
var firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'height': '100%',
'width': slider.width() + 'px'
});
firstSlice.animate({ opacity:'1.0' }, (settings.animSpeed*2), '', function(){ slider.trigger('nivo:animFinished'); });
}
else if(settings.effect == 'slideInRight' || vars.randAnim == 'slideInRight'){
createSlices(slider, settings, vars);
var firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'height': '100%',
'width': '0px',
'opacity': '1'
});
firstSlice.animate({ width: slider.width() + 'px' }, (settings.animSpeed*2), '', function(){ slider.trigger('nivo:animFinished'); });
}
else if(settings.effect == 'slideInLeft' || vars.randAnim == 'slideInLeft'){
createSlices(slider, settings, vars);
var firstSlice = $('.nivo-slice:first', slider);
firstSlice.css({
'height': '100%',
'width': '0px',
'opacity': '1',
'left': '',
'right': '0px'
});
firstSlice.animate({ width: slider.width() + 'px' }, (settings.animSpeed*2), '', function(){
// Reset positioning
firstSlice.css({
'left': '0px',
'right': ''
});
slider.trigger('nivo:animFinished');
});
}
else if(settings.effect == 'boxRandom' || vars.randAnim == 'boxRandom'){
createBoxes(slider, settings, vars);
var totalBoxes = settings.boxCols * settings.boxRows;
var i = 0;
var timeBuff = 0;
var boxes = shuffle($('.nivo-box', slider));
boxes.each(function(){
var box = $(this);
if(i == totalBoxes-1){
setTimeout(function(){
box.animate({ opacity:'1' }, settings.animSpeed, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + timeBuff));
} else {
setTimeout(function(){
box.animate({ opacity:'1' }, settings.animSpeed);
}, (100 + timeBuff));
}
timeBuff += 20;
i++;
});
}
else if(settings.effect == 'boxRain' || vars.randAnim == 'boxRain' || settings.effect == 'boxRainReverse' || vars.randAnim == 'boxRainReverse' ||
settings.effect == 'boxRainGrow' || vars.randAnim == 'boxRainGrow' || settings.effect == 'boxRainGrowReverse' || vars.randAnim == 'boxRainGrowReverse'){
createBoxes(slider, settings, vars);
var totalBoxes = settings.boxCols * settings.boxRows;
var i = 0;
var timeBuff = 0;
// Split boxes into 2D array
var rowIndex = 0;
var colIndex = 0;
var box2Darr = new Array();
box2Darr[rowIndex] = new Array();
var boxes = $('.nivo-box', slider);
if(settings.effect == 'boxRainReverse' || vars.randAnim == 'boxRainReverse' ||
settings.effect == 'boxRainGrowReverse' || vars.randAnim == 'boxRainGrowReverse'){
boxes = $('.nivo-box', slider)._reverse();
}
boxes.each(function(){
box2Darr[rowIndex][colIndex] = $(this);
colIndex++;
if(colIndex == settings.boxCols){
rowIndex++;
colIndex = 0;
box2Darr[rowIndex] = new Array();
}
});
// Run animation
for(var cols = 0; cols < (settings.boxCols * 2); cols++){
var prevCol = cols;
for(var rows = 0; rows < settings.boxRows; rows++){
if(prevCol >= 0 && prevCol < settings.boxCols){
/* Due to some weird JS bug with loop vars
being used in setTimeout, this is wrapped
with an anonymous function call */
(function(row, col, time, i, totalBoxes) {
var box = $(box2Darr[row][col]);
var w = box.width();
var h = box.height();
if(settings.effect == 'boxRainGrow' || vars.randAnim == 'boxRainGrow' ||
settings.effect == 'boxRainGrowReverse' || vars.randAnim == 'boxRainGrowReverse'){
box.width(0).height(0);
}
if(i == totalBoxes-1){
setTimeout(function(){
box.animate({ opacity:'1', width:w, height:h }, settings.animSpeed/1.3, '', function(){ slider.trigger('nivo:animFinished'); });
}, (100 + time));
} else {
setTimeout(function(){
box.animate({ opacity:'1', width:w, height:h }, settings.animSpeed/1.3);
}, (100 + time));
}
})(rows, prevCol, timeBuff, i, totalBoxes);
i++;
}
prevCol--;
}
timeBuff += 100;
}
}
}
// Shuffle an array
var shuffle = function(arr){
for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
return arr;
}
// For debugging
var trace = function(msg){
if (this.console && typeof console.log != "undefined")
console.log(msg);
}
// Start / Stop
this.stop = function(){
if(!$(element).data('nivo:vars').stop){
$(element).data('nivo:vars').stop = true;
trace('Stop Slider');
}
}
this.start = function(){
if($(element).data('nivo:vars').stop){
$(element).data('nivo:vars').stop = false;
trace('Start Slider');
}
}
//Trigger the afterLoad callback
settings.afterLoad.call(this);
return this;
};
$.fn.nivoSlider = function(options) {
return this.each(function(key, value){
var element = $(this);
// Return early if this element already has a plugin instance
if (element.data('nivoslider')) return element.data('nivoslider');
// Pass options to plugin constructor
var nivoslider = new NivoSlider(this, options);
// Store plugin object in this element's data
element.data('nivoslider', nivoslider);
});
};
//Default settings
$.fn.nivoSlider.defaults = {
effect: 'random',
slices: 15,
boxCols: 8,
boxRows: 4,
animSpeed: 500,
pauseTime: 3000,
startSlide: 0,
directionNav: true,
directionNavHide: true,
controlNav: true,
controlNavThumbs: false,
controlNavThumbsFromRel: false,
controlNavThumbsSearch: '.jpg',
controlNavThumbsReplace: '_thumb.jpg',
keyboardNav: true,
pauseOnHover: true,
manualAdvance: false,
captionOpacity: 1.0,
prevText: 'Prev',
nextText: 'Next',
beforeChange: function(){},
afterChange: function(){},
slideshowEnd: function(){},
lastSlide: function(){},
afterLoad: function(){}
};
$.fn._reverse = [].reverse;
})(jQuery);
I was using the wrong version of jQuery. I am now using version 1.5.2.
The live function was deprecated in version 1.7. The latest version is 1.9.
Nivo Slider uses the live function. I was running into the same issue as the one stated until I realized our site was grabbing the jQuery code form the web instead of from a .js file living on our site.
I'm using version 1.7.1 and Nivo Slider is working fine now.

Categories

Resources