How to make jquery script work after Ajax dom append? - javascript

Ye, i know about "on" method and most of answers here about "on" are not specific. Can someone help me with this code?
$(function(){
var pagePositon = 0,
sectionsSeclector = 'article#sector',
$scrollItems = $(sectionsSeclector),
offsetTolorence = 30,
pageMaxPosition = $scrollItems.length - 1;
//Map the sections:
$scrollItems.each(function(index,ele) { $(ele).attr("debog",index).data("pos",index); });
// Bind to scroll
$(window).bind('scroll',upPos);
//Move on click:
$(document).keypress(function(e) {
if (e.which == 100 && pagePositon+1 <= pageMaxPosition) {
pagePositon++;
$('html, body').stop().animate({
scrollTop: $scrollItems.eq(pagePositon).offset().top
}, 300);
}
if (e.which == 97 && pagePositon-1 >= 0) {
pagePositon--;
$('html, body').stop().animate({
scrollTop: $scrollItems.eq(pagePositon).offset().top
}, 300);
return false;
}
});
//Update position func:
function upPos(){
var fromTop = $(this).scrollTop();
var $cur = null;
$scrollItems.each(function(index,ele){
if ($(ele).offset().top < fromTop + offsetTolorence) $cur = $(ele);
});
if ($cur != null && pagePositon != $cur.data('pos')) {
pagePositon = $cur.data('pos');
}
}
});
When you press "d" or "a" it goes to next or prev with id="sector" and that's fine. But occasionally, after Ajax Call and after append of new articles, script can't move to them. I know that they are not binded (after dom refresh) and how to make that script work after Ajax dom change?

Solved:
$(function(){
var pagePositon = 0,
sectionsSeclector = 'article#sector',
$scrollItems = $(sectionsSeclector),
offsetTolorence = 30,
pageMaxPosition = $scrollItems.length - 1;
//Map the sections:
// Bind to scroll
//Move on click:
$(document).on('keypress', function(e) {
$scrollItems = $(sectionsSeclector);
pageMaxPosition = $scrollItems.length - 1;
$scrollItems.each(function(index,ele) { $(ele).attr("debog",index).data("pos",index); });
$(window).bind('scroll',upPos);
if (e.which == 100 && pagePositon+1 <= pageMaxPosition) {
pagePositon++;
$('html, body').stop().animate({
scrollTop: $scrollItems.eq(pagePositon).offset().top
}, 300);
}
if (e.which == 97 && pagePositon-1 >= 0) {
pagePositon--;
$('html, body').stop().animate({
scrollTop: $scrollItems.eq(pagePositon).offset().top
}, 300);
return false;
}
});
//Update position func:
function upPos(){
var fromTop = $(this).scrollTop();
var $cur = null;
$scrollItems.each(function(index,ele){
if ($(ele).offset().top < fromTop + offsetTolorence) $cur = $(ele);
});
if ($cur != null && pagePositon != $cur.data('pos')) {
pagePositon = $cur.data('pos');
}
}
});

Related

Uncaught TypeError: Cannot read property 'offset' of undefined

I am getting Uncaught TypeError: Cannot read property 'offset' of undefined
Before that i was getting same exception for 'top' from same block. I fixed it in one way now, I am getting the error with 'offset'.
Here is my code.
var ssSmoothScroll = function() {
$('.smoothscroll').on('click', function (e) {
if (this.hash !== "" && this.pathname == window.location.pathname) {
var target = this.hash;
// $target = $(target);
e.preventDefault();
e.stopPropagation();
var topOffset = 0; //#top should default to 0 so no need to calculate the difference between top and top :)
if (target != "#top") { //If the target is not "#top", then calculate topOffset
var topOffset = $(target).offset().top;
}
}
else{
var target = this.hash,
$target = $(target);
e.preventDefault();
e.stopPropagation();
}
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, cfg.scrollDuration, 'swing', function () {
window.location.hash = target;
});
});
};
Any help is appreciated :)
Because you define $target inside the else statement so if it does not go into the else it is undefined.
You need to set $target outside of the else
if (target != "#top") {
// you do not set it here
...
else{
var target = this.hash, // <-- not sure why you are declaring target again....
$target = $(target); // you set it here
...
}
Try this code instead, I think this works
var ssSmoothScroll = function() {
$(".smoothscroll").on("click", function(e) {
if (this.hash !== "" && this.pathname == window.location.pathname) {
var target = this.hash,
$target = $(target);
// $target = $(target);
e.preventDefault();
e.stopPropagation();
var topOffset = 0; //#top should default to 0 so no need to calculate the difference between top and top :)
if (target != "#top") {
//If the target is not "#top", then calculate topOffset
topOffset = $(target).offset().top;
}
$("html, body")
.stop()
.animate(
{
scrollTop: $target.offset().top
},
cfg.scrollDuration,
"swing",
function() {
window.location.hash = target;
}
);
}
});
};

jQuery Full Page transition scroll

so I want to implement a full page transition scroll with jQuery. I know that there are plugins for this, but I need a custom code in my case.
//new script
<script>
$(document).ready(function(){
// http://stackoverflow.com/questions/4770025/how-to-disable-scrolling-temporarily
// left: 37, up: 38, right: 39, down: 40,
// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
var keys = {37: 1, 38: 1, 39: 1, 40: 1};
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
function preventDefaultForScrollKeys(e) {
if (keys[e.keyCode]) {
preventDefault(e);
return false;
}
}
function disableScroll() {
if (window.addEventListener) // older FF
window.addEventListener('DOMMouseScroll', preventDefault, false);
window.onwheel = preventDefault; // modern standard
window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE
window.ontouchmove = preventDefault; // mobile
document.onkeydown = preventDefaultForScrollKeys;
}
function enableScroll() {
if (window.removeEventListener)
window.removeEventListener('DOMMouseScroll', preventDefault, false);
window.onmousewheel = document.onmousewheel = null;
window.onwheel = null;
window.ontouchmove = null;
document.onkeydown = null;
}
/* $(window).scroll(function(){
}); */
var lastScrollTop = 0;
$(window).scroll(function(event){
var st = $(this).scrollTop();
if (st > lastScrollTop){
// downscroll code
console.log('down');
if (($(this).scrollTop() >940) && ($(this).scrollTop() <1000)){
disableScroll();
$('html, body').animate({ scrollTop: $(".bg1").offset().top}, 2000);
enableScroll();
}
if ($(this).scrollTop() >1548){
disableScroll();
$('html, body').animate({ scrollTop: $(".bg2").offset().top}, 2000);
enableScroll();
}
} else {
// upscroll code
console.log('up');
/* if ($(this).scrollTop() >1548){
disableScroll();
$('html, body').animate({ scrollTop: $(".bg").offset().top}, 2000);
enableScroll();
} */
}
lastScrollTop = st;
});
}); //document.ready
</script>
So this is my script. It checks whether the scroll is up or down, then starting on the specified pixels it starts transitioning. The beginning is happening very well.The first transition is happening. However after that no matter if I scroll up or down it always transits back to the position of bg1. If I scroll very intensely sometimes the scrolling to the bg2 happens. What is the problem of my code?
Here is a working code with comments in it and the sources I used.
//$(document).ready(function(){ //disables all the scrolling
// $('body,html').css('overflow', 'hidden');
// });
// http://stackoverflow.com/questions/4770025/how-to-disable-scrolling-temporarily
// left: 37, up: 38, right: 39, down: 40,
// spacebar: 32, pageup: 33, pagedown: 34, end: 35, home: 36
var keys = {37: 1, 38: 1, 39: 1, 40: 1};
function preventDefault(e) {
e = e || window.event;
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
function preventDefaultForScrollKeys(e) {
if (keys[e.keyCode]) {
preventDefault(e);
return false;
}
}
function disableScroll() {
if (window.addEventListener) // older FF
window.addEventListener('DOMMouseScroll', preventDefault, false);
window.onwheel = preventDefault; // modern standard
window.onmousewheel = document.onmousewheel = preventDefault; // older browsers, IE
window.ontouchmove = preventDefault; // mobile
document.onkeydown = preventDefaultForScrollKeys;
}
function enableScroll() {
if (window.removeEventListener)
window.removeEventListener('DOMMouseScroll', preventDefault, false);
window.onmousewheel = document.onmousewheel = null;
window.onwheel = null;
window.ontouchmove = null;
document.onkeydown = null;
}
//http://stackoverflow.com/questions/33838956/jquery-full-page-scroll-without-plugin
var currentLocation = 'firstPage';
// No need to set these inside the event listener since they are always the same.
var firstHeight = $('#firstPage').offset().top,
secondHeight = $('#secondPage').offset().top,
thirdHeight = $('#thirdPage').offset().top,
fourthHeight = $('#fourthPage').offset().top,
fifthHeight = $('#fifthPage').offset().top,
sixthHeight = $('#sixthPage').offset().top,
seventhHeight = $('#seventhPage').offset().top,
eightHeight = $('#eightPage').offset().top,
ninthHeight = $('#ninthPage').offset().top;
// Helper so we can check if the scroll is triggered by user or by animation.
var autoScrolling = false;
$(document).scroll(function(e){
var scrolled = $(window).scrollTop();
// Only check if the user scrolled
if (!autoScrolling) {
if (scrolled > 1 && currentLocation == 'firstPage') {
scrollPage(secondHeight, 'secondPage');
}
else if (scrolled > secondHeight + 1 && currentLocation == 'secondPage') {
scrollPage(thirdHeight, 'thirdPage');
}
else if (scrolled > thirdHeight + 1 && currentLocation == 'thirdPage') {
scrollPage(fourthHeight, 'fourthPage');
}
else if (scrolled > fourthHeight + 1 && currentLocation == 'fourthPage') {
scrollPage(fifthHeight, 'fifthPage');
}
else if (scrolled > fifthHeight + 1 && currentLocation == 'fifthPage') {
scrollPage(sixthHeight, 'sixthPage');
}
else if (scrolled > sixthHeight + 1 && currentLocation == 'sixthPage') {
scrollPage(seventhHeight, 'seventhPage');
}
else if (scrolled > seventhHeight + 1 && currentLocation == 'seventhPage') {
scrollPage(eightHeight, 'eightPage');
}
else if (scrolled > eightHeight + 1 && currentLocation == 'eightPage') {
scrollPage(ninthHeight, 'ninthPage');
}
else if (scrolled < ninthHeight - 1 && currentLocation == 'ninthPage') {
scrollPage(eightHeight, 'eightPage');
}
else if (scrolled < eightHeight - 1 && currentLocation == 'eightPage') {
scrollPage(seventhHeight, 'seventhPage');
}
else if (scrolled < seventhHeight - 1 && currentLocation == 'seventhPage') {
scrollPage(sixthHeight, 'sixthPage');
}
else if (scrolled < sixthHeight - 1 && currentLocation == 'sixthPage') {
scrollPage(fifthHeight, 'fifthPage');
}
else if (scrolled < fifthHeight - 1 && currentLocation == 'fifthPage') {
scrollPage(fourthHeight, 'fourthPage');
}
else if (scrolled < fourthHeight - 1 && currentLocation == 'fourthPage') {
scrollPage(thirdHeight, 'thirdPage');
}
else if (scrolled < thirdHeight - 1 && currentLocation == 'thirdPage') {
scrollPage(secondHeight, 'secondPage');
}
else if (scrolled < secondHeight - 1 && currentLocation == 'secondPage') {
scrollPage(firstHeight, 'firstPage');
}
}//autoScrolling IF
// Since they all have the same animation, you can avoid repetition
function scrollPage(nextHeight, page) {
currentLocation = page;
// At this point, the page will start scrolling by the animation
// So we switch this var so the listener does not trigger all the if/else
autoScrolling = true;
disableScroll();
$('body,html').animate({scrollTop:nextHeight}, 500, function () {
// Once the animation is over, we can reset the helper.
// Now it is back to detecting user scroll.
autoScrolling = false;
enableScroll();
});
}
//$('h1').html(scrolled);
//$('h1').append("/" + secondHeight);
//$('h1').append("/" + thirdHeight);
})//document.ready

How do I map up and down-arrow keys to page-up and page-down keys

I pieced together this block of code to advance the user further left/right than normally. It works well and I'd like the same for up/down. If someone is in the know, I'd be grateful for a reply! Thanks all.
$(document).keydown(function(e) {
if (e.keyCode == 37) {
var leftPos = $('.jcarousel').scrollLeft();
$(".jcarousel").animate({
scrollLeft: leftPos - 800
}, 800);
return false;
}
if (e.keyCode == 39) {
var leftPos = $('.jcarousel').scrollLeft();
$(".jcarousel").animate({
scrollLeft: leftPos + 800
}, 800);
return false;
}
if (e.keyCode == 40) {
var topPos = $('.wrapper').scrollTop();
// DO SOMETHING, BUT WHAT?
return false;
}
if (e.keyCode == 38) {
// DO SOMETHING, BUT WHAT?
return false;
}
});
So here's the final chunk that does as it's supposed to. (figured it out...)
<script>
$(document).keydown(function(e){
if (e.keyCode == 37) {
var leftPos = $('.jcarousel').scrollLeft();
$(".jcarousel").animate({scrollLeft: leftPos - 1200}, 800);
return false;
}
if (e.keyCode == 39) {
var leftPos = $('.jcarousel').scrollLeft();
$(".jcarousel").animate({scrollLeft: leftPos + 1200}, 800);
return false;
}
if (e.keyCode == 40) { //Down
var topPos = $(window).scrollTop();
$(window).animate({scrollTop: topPos + 800}, 600);
$(".jcarousel").animate({scrollLeft: 0}, 800);
return false;
}
if (e.keyCode == 38) { //Up
var topPos = $(window).scrollTop();
$(window).animate({scrollTop: topPos - 800}, 600);
$(".jcarousel").animate({scrollLeft: 0}, 800);
return false;
}
});
</script>

Callback function to add newly loaded images to a roll

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...!

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