Page Scroll Effects - VelocityJS - (Page Anchors with Data-hijacking enabled) - javascript

I'm stuck with my page scroll effects.
This is what I've got so far - https://codepen.io/DCRSLG/pen/jzYJeY
$(document).ready(function($) {
//variables
var hijacking = $('body').data('hijacking'),
animationType = $('body').data('animation'),
delta = 0,
scrollThreshold = 5,
actual = 1,
animating = false;
//DOM elements
var sectionsAvailable = $('.cd-section'),
verticalNav = $('.cd-vertical-nav'),
prevArrow = verticalNav.find('a.cd-prev'),
nextArrow = verticalNav.find('a.cd-next');
//check the media query and bind corresponding events
var MQ = deviceType(),
bindToggle = false;
bindEvents(MQ, true);
$(window).on('resize', function() {
MQ = deviceType();
bindEvents(MQ, bindToggle);
if (MQ == 'mobile') bindToggle = true;
if (MQ == 'desktop') bindToggle = false;
});
function bindEvents(MQ, bool) {
if (MQ == 'desktop' && bool) {
//bind the animation to the window scroll event, arrows click and keyboard
if (hijacking == 'on') {
initHijacking();
$(window).on('DOMMouseScroll mousewheel', scrollHijacking);
} else {
scrollAnimation();
$(window).on('scroll', scrollAnimation);
}
prevArrow.on('click', prevSection);
nextArrow.on('click', nextSection);
$('a[href*="#"]').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
var target = $(this).attr('href');
$(target).velocity('scroll', {
duration: 3000,
offset: 0,
easing: 'ease-in-out',
mobileHA: false
});
});
$(document).on('keydown', function(event) {
if (event.which == '40' && !nextArrow.hasClass('inactive')) {
event.preventDefault();
nextSection();
} else if (event.which == '38' && (!prevArrow.hasClass('inactive') || (prevArrow.hasClass('inactive') && $(window).scrollTop() != sectionsAvailable.eq(0).offset().top))) {
event.preventDefault();
prevSection();
}
});
//set navigation arrows visibility
checkNavigation();
} else if (MQ == 'mobile') {
//reset and unbind
resetSectionStyle();
$(window).off('DOMMouseScroll mousewheel', scrollHijacking);
$(window).off('scroll', scrollAnimation);
prevArrow.off('click', prevSection);
nextArrow.off('click', nextSection);
$(document).off('keydown');
}
}
function scrollAnimation() {
//normal scroll - use requestAnimationFrame (if defined) to optimize performance
(!window.requestAnimationFrame) ? animateSection(): window.requestAnimationFrame(animateSection);
}
function animateSection() {
var scrollTop = $(window).scrollTop(),
windowHeight = $(window).height(),
windowWidth = $(window).width();
sectionsAvailable.each(function() {
var actualBlock = $(this),
offset = scrollTop - actualBlock.offset().top;
//according to animation type and window scroll, define animation parameters
var animationValues = setSectionAnimation(offset, windowHeight, animationType);
transformSection(actualBlock.children('div'), animationValues[0], animationValues[1], animationValues[2], animationValues[3], animationValues[4]);
(offset >= 0 && offset < windowHeight) ? actualBlock.addClass('visible'): actualBlock.removeClass('visible');
});
checkNavigation();
}
function transformSection(element, translateY, scaleValue, rotateXValue, opacityValue, boxShadow) {
//transform sections - normal scroll
element.velocity({
translateY: translateY + 'vh',
scale: scaleValue,
rotateX: rotateXValue,
opacity: opacityValue,
boxShadowBlur: boxShadow + 'px',
translateZ: 0,
}, 0);
}
function initHijacking() {
// initialize section style - scrollhijacking
var visibleSection = sectionsAvailable.filter('.visible'),
topSection = visibleSection.prevAll('.cd-section'),
bottomSection = visibleSection.nextAll('.cd-section'),
animationParams = selectAnimation(animationType, false),
animationVisible = animationParams[0],
animationTop = animationParams[1],
animationBottom = animationParams[2];
visibleSection.children('div').velocity(animationVisible, 1, function() {
visibleSection.css('opacity', 1);
topSection.css('opacity', 1);
bottomSection.css('opacity', 1);
});
topSection.children('div').velocity(animationTop, 0);
bottomSection.children('div').velocity(animationBottom, 0);
}
function scrollHijacking(event) {
// on mouse scroll - check if animate section
if (event.originalEvent.detail < 0 || event.originalEvent.wheelDelta > 0) {
delta--;
(Math.abs(delta) >= scrollThreshold) && prevSection();
} else {
delta++;
(delta >= scrollThreshold) && nextSection();
}
return false;
}
function prevSection(event) {
//go to previous section
typeof event !== 'undefined' && event.preventDefault();
var visibleSection = sectionsAvailable.filter('.visible'),
middleScroll = (hijacking == 'off' && $(window).scrollTop() != visibleSection.offset().top) ? true : false;
visibleSection = middleScroll ? visibleSection.next('.cd-section') : visibleSection;
var animationParams = selectAnimation(animationType, middleScroll, 'prev');
unbindScroll(visibleSection.prev('.cd-section'), animationParams[3]);
if (!animating && !visibleSection.is(":first-child")) {
animating = true;
visibleSection.removeClass('visible').children('div').velocity(animationParams[2], animationParams[3], animationParams[4])
.end().prev('.cd-section').addClass('visible').children('div').velocity(animationParams[0], animationParams[3], animationParams[4], function() {
animating = false;
if (hijacking == 'off') $(window).on('scroll', scrollAnimation);
});
actual = actual - 1;
}
resetScroll();
}
function nextSection(event) {
//go to next section
typeof event !== 'undefined' && event.preventDefault();
var visibleSection = sectionsAvailable.filter('.visible'),
middleScroll = (hijacking == 'off' && $(window).scrollTop() != visibleSection.offset().top) ? true : false;
var animationParams = selectAnimation(animationType, middleScroll, 'next');
unbindScroll(visibleSection.next('.cd-section'), animationParams[3]);
if (!animating && !visibleSection.is(":last-of-type")) {
animating = true;
visibleSection.removeClass('visible').children('div').velocity(animationParams[1], animationParams[3], animationParams[4])
.end().next('.cd-section').addClass('visible').children('div').velocity(animationParams[0], animationParams[3], animationParams[4], function() {
animating = false;
if (hijacking == 'off') $(window).on('scroll', scrollAnimation);
});
actual = actual + 1;
}
resetScroll();
}
function unbindScroll(section, time) {
//if clicking on navigation - unbind scroll and animate using custom velocity animation
if (hijacking == 'off') {
$(window).off('scroll', scrollAnimation);
(animationType == 'catch') ? $('body, html').scrollTop(section.offset().top): section.velocity("scroll", {
duration: time
});
}
}
function resetScroll() {
delta = 0;
checkNavigation();
}
function checkNavigation() {
//update navigation arrows visibility
(sectionsAvailable.filter('.visible').is(':first-of-type')) ? prevArrow.addClass('inactive'): prevArrow.removeClass('inactive');
(sectionsAvailable.filter('.visible').is(':last-of-type')) ? nextArrow.addClass('inactive'): nextArrow.removeClass('inactive');
}
function resetSectionStyle() {
//on mobile - remove style applied with jQuery
sectionsAvailable.children('div').each(function() {
$(this).attr('style', '');
});
}
function deviceType() {
//detect if desktop/mobile
return window.getComputedStyle(document.querySelector('body'), '::before').getPropertyValue('content').replace(/"/g, "").replace(/'/g, "");
}
function selectAnimation(animationName, middleScroll, direction) {
// select section animation - scrollhijacking
var animationVisible = 'translateNone',
animationTop = 'translateUp',
animationBottom = 'translateDown',
easing = 'ease',
animDuration = 800;
switch (animationName) {
case 'gallery':
animDuration = 1500;
if (middleScroll) {
animationTop = 'scaleDown.moveUp.scroll';
animationVisible = 'scaleUp.moveUp.scroll';
animationBottom = 'scaleDown.moveDown.scroll';
} else {
animationVisible = (direction == 'next') ? 'scaleUp.moveUp' : 'scaleUp.moveDown';
animationTop = 'scaleDown.moveUp';
animationBottom = 'scaleDown.moveDown';
}
break;
}
return [animationVisible, animationTop, animationBottom, animDuration, easing];
}
function setSectionAnimation(sectionOffset, windowHeight, animationName) {
// select section animation - normal scroll
var scale = 1,
translateY = 100,
rotateX = '0deg',
opacity = 1,
boxShadowBlur = 0;
if (sectionOffset >= -windowHeight && sectionOffset <= 0) {
// section entering the viewport
translateY = (-sectionOffset) * 100 / windowHeight;
switch (animationName) {
case 'gallery':
if (sectionOffset >= -windowHeight && sectionOffset < -0.9 * windowHeight) {
scale = -sectionOffset / windowHeight;
translateY = (-sectionOffset) * 100 / windowHeight;
boxShadowBlur = 400 * (1 + sectionOffset / windowHeight);
} else if (sectionOffset >= -0.9 * windowHeight && sectionOffset < -0.1 * windowHeight) {
scale = 0.9;
translateY = -(9 / 8) * (sectionOffset + 0.1 * windowHeight) * 100 / windowHeight;
boxShadowBlur = 40;
} else {
scale = 1 + sectionOffset / windowHeight;
translateY = 0;
boxShadowBlur = -400 * sectionOffset / windowHeight;
}
break;
}
} else if (sectionOffset > 0 && sectionOffset <= windowHeight) {
//section leaving the viewport - still has the '.visible' class
translateY = (-sectionOffset) * 100 / windowHeight;
switch (animationName) {
case 'gallery':
if (sectionOffset >= 0 && sectionOffset < 0.1 * windowHeight) {
scale = (windowHeight - sectionOffset) / windowHeight;
translateY = -(sectionOffset / windowHeight) * 100;
boxShadowBlur = 400 * sectionOffset / windowHeight;
} else if (sectionOffset >= 0.1 * windowHeight && sectionOffset < 0.9 * windowHeight) {
scale = 0.9;
translateY = -(9 / 8) * (sectionOffset - 0.1 * windowHeight / 9) * 100 / windowHeight;
boxShadowBlur = 40;
} else {
scale = sectionOffset / windowHeight;
translateY = -100;
boxShadowBlur = 400 * (1 - sectionOffset / windowHeight);
}
break;
}
} else if (sectionOffset < -windowHeight) {
translateY = 100;
switch (animationName) {
case 'gallery':
scale = 1;
break;
}
} else {
//section not visible anymore
translateY = -100;
switch (animationName) {
case 'gallery':
scale = 1;
break;
}
}
return [translateY, scale, rotateX, opacity, boxShadowBlur];
}
});
/* Custom effects registration - feature available in the Velocity UI pack */
//gallery
$.Velocity
.RegisterEffect("scaleDown.moveUp", {
defaultDuration: 1,
calls: [
[{
translateY: '-10%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.20],
[{
translateY: '-100%'
}, 0.60],
[{
translateY: '-100%',
scale: '1',
boxShadowBlur: '0'
}, 0.20]
]
});
$.Velocity
.RegisterEffect("scaleDown.moveUp.scroll", {
defaultDuration: 1,
calls: [
[{
translateY: '-100%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.60],
[{
translateY: '-100%',
scale: '1',
boxShadowBlur: '0'
}, 0.40]
]
});
$.Velocity
.RegisterEffect("scaleUp.moveUp", {
defaultDuration: 1,
calls: [
[{
translateY: '90%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.20],
[{
translateY: '0%'
}, 0.60],
[{
translateY: '0%',
scale: '1',
boxShadowBlur: '0'
}, 0.20]
]
});
$.Velocity
.RegisterEffect("scaleUp.moveUp.scroll", {
defaultDuration: 1,
calls: [
[{
translateY: '0%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.60],
[{
translateY: '0%',
scale: '1',
boxShadowBlur: '0'
}, 0.40]
]
});
$.Velocity
.RegisterEffect("scaleDown.moveDown", {
defaultDuration: 1,
calls: [
[{
translateY: '10%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.20],
[{
translateY: '100%'
}, 0.60],
[{
translateY: '100%',
scale: '1',
boxShadowBlur: '0'
}, 0.20]
]
});
$.Velocity
.RegisterEffect("scaleDown.moveDown.scroll", {
defaultDuration: 1,
calls: [
[{
translateY: '100%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.60],
[{
translateY: '100%',
scale: '1',
boxShadowBlur: '0'
}, 0.40]
]
});
$.Velocity
.RegisterEffect("scaleUp.moveDown", {
defaultDuration: 1,
calls: [
[{
translateY: '-90%',
scale: '0.9',
boxShadowBlur: '40px'
}, 0.20],
[{
translateY: '0%'
}, 0.60],
[{
translateY: '0%',
scale: '1',
boxShadowBlur: '0'
}, 0.20]
]
});
I'm trying to get it so the Dots on the right hand side can be a reference to scroll down to each section like this:
https://codyhouse.co/demo/vertical-fixed-navigation/index.html
$('a[href*="#"]').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
var target = $(this).attr('href');
$(target).velocity('scroll', {
duration: 3000,
offset: 0,
easing: 'ease-in-out',
mobileHA: false
});
});
I can get it to work using the above code providing I disable data-hijacking on the scroll, does anyone know of a way to get this to work while keep data-hijacking enabled?

Related

Slider navigation dots not getting highlighted

My slider is partly made of dots indicating which slide is active. So when a slide gets activated, its associated dot should become blue.
But I could not get the last (third) dot to be highlighted when its slide is comes in.
Can anybody help me sort things out?
Thank you.
My code so far:
var prevDot = 0;
function init() {
var elem = document.getElementById('mySwipe');
window.mySwipe = Swipe(elem, {
// startSlide: 4,
// auto: 3000,
// continuous: true,
// disableScroll: true,
// stopPropagation: true,
// callback: function(index, element) {},
transitionEnd: function(index, element) {
$(".swipeDot").find("li").eq(prevDot).removeClass("dot_select");
prevDot = (index == 0 || index == 2) ? 0 : 1;
$(".swipeDot").find("li").eq(prevDot).addClass("dot_select");
console.log(index);
}
});
//$(".swipe-wrap").find("div").eq(2).find("span").css({backgroundImage:"url('../images/p006_img_2.png')"})
$("#prevBtn").click(function() {
window.mySwipe.prev();
});
$("#nextBtn").click(function() {
window.mySwipe.next();
});
$(".swipeDot li").each(function(index) {
$(this).attr("slideIndex", index);
});
$(".swipeDot li").click(function() {
var slideIndex = $(this).attr("slideIndex");
window.mySwipe.slide(slideIndex);
});
}
$(document).ready(init);
function Swipe(container, options) {
console.log(container);
"use strict";
// utilities
var noop = function() {}; // simple no operation function
var offloadFn = function(fn) {
setTimeout(fn || noop, 0)
}; // offload a functions execution
// check browser capabilities
var browser = {
addEventListener: !!window.addEventListener,
touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
transitions: (function(temp) {
var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
for (var i in props)
if (temp.style[props[i]] !== undefined) return true;
return false;
})(document.createElement('swipe'))
};
// quit if no root element
if (!container) return;
var element = container.children[0];
var slides, slidePos, width, length;
options = options || {};
var index = parseInt(options.startSlide, 10) || 0;
var speed = options.speed || 300;
options.continuous = options.continuous !== undefined ? options.continuous : true;
function setup() {
// cache slides
slides = element.children;
length = slides.length;
// set continuous to false if only one slide
if (slides.length < 2) options.continuous = false;
//special case if two slides
if (browser.transitions && options.continuous && slides.length < 3) {
element.appendChild(slides[0].cloneNode(true));
element.appendChild(element.children[1].cloneNode(true));
slides = element.children;
}
// create an array to store current positions of each slide
slidePos = new Array(slides.length);
// determine width of each slide
width = container.offsetWidth;
element.style.width = (slides.length * width) + 'px';
// stack elements
var pos = slides.length;
while (pos--) {
var slide = slides[pos];
slide.style.width = width + 'px';
slide.setAttribute('data-index', pos);
if (browser.transitions) {
slide.style.left = (pos * -width) + 'px';
move(pos, index > pos ? -width : (index < pos ? width : 0), 0);
}
}
// reposition elements before and after index
if (options.continuous && browser.transitions) {
move(circle(index - 1), -width, 0);
move(circle(index + 1), width, 0);
}
if (!browser.transitions) element.style.left = (index * -width) + 'px';
container.style.visibility = 'visible';
}
function prev() {
if (options.continuous) slide(index - 1);
else if (index) slide(index - 1);
}
function next() {
if (options.continuous) slide(index + 1);
else if (index < slides.length - 1) slide(index + 1);
}
function circle(index) {
// a simple positive modulo using slides.length
return (slides.length + (index % slides.length)) % slides.length;
}
function slide(to, slideSpeed) {
// do nothing if already on requested slide
if (index == to) return;
if (browser.transitions) {
var direction = Math.abs(index - to) / (index - to); // 1: backward, -1: forward
// get the actual position of the slide
if (options.continuous) {
var natural_direction = direction;
direction = -slidePos[circle(to)] / width;
// if going forward but to < index, use to = slides.length + to
// if going backward but to > index, use to = -slides.length + to
if (direction !== natural_direction) to = -direction * slides.length + to;
}
var diff = Math.abs(index - to) - 1;
// move all the slides between index and to in the right direction
while (diff--) move(circle((to > index ? to : index) - diff - 1), width * direction, 0);
to = circle(to);
move(index, width * direction, slideSpeed || speed);
move(to, 0, slideSpeed || speed);
if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place
} else {
to = circle(to);
animate(index * -width, to * -width, slideSpeed || speed);
//no fallback for a circular continuous if the browser does not accept transitions
}
index = to;
offloadFn(options.callback && options.callback(index, slides[index]));
}
function move(index, dist, speed) {
translate(index, dist, speed);
slidePos[index] = dist;
}
function translate(index, dist, speed) {
var slide = slides[index];
var style = slide && slide.style;
if (!style) return;
style.webkitTransitionDuration =
style.MozTransitionDuration =
style.msTransitionDuration =
style.OTransitionDuration =
style.transitionDuration = speed + 'ms';
style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
style.msTransform =
style.MozTransform =
style.OTransform = 'translateX(' + dist + 'px)';
}
function animate(from, to, speed) {
// if not an animation, just reposition
if (!speed) {
element.style.left = to + 'px';
return;
}
var start = +new Date;
var timer = setInterval(function() {
var timeElap = +new Date - start;
if (timeElap > speed) {
element.style.left = to + 'px';
if (delay) begin();
options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
clearInterval(timer);
return;
}
element.style.left = (((to - from) * (Math.floor((timeElap / speed) * 100) / 100)) + from) + 'px';
}, 4);
}
// setup auto slideshow
var delay = options.auto || 0;
var interval;
function begin() {
interval = setTimeout(next, delay);
}
function stop() {
delay = 0;
clearTimeout(interval);
}
// setup initial vars
var start = {};
var delta = {};
var isScrolling;
// setup event capturing
var events = {
handleEvent: function(event) {
switch (event.type) {
case 'touchstart':
this.start(event);
break;
case 'touchmove':
this.move(event);
break;
case 'touchend':
offloadFn(this.end(event));
break;
case 'webkitTransitionEnd':
case 'msTransitionEnd':
case 'oTransitionEnd':
case 'otransitionend':
case 'transitionend':
offloadFn(this.transitionEnd(event));
break;
case 'resize':
offloadFn(setup);
break;
}
if (options.stopPropagation) event.stopPropagation();
},
start: function(event) {
var touches = event.touches[0];
// measure start values
start = {
// get initial touch coords
x: touches.pageX,
y: touches.pageY,
// store time to determine touch duration
time: +new Date
};
// used for testing first move event
isScrolling = undefined;
// reset delta and end measurements
delta = {};
// attach touchmove and touchend listeners
element.addEventListener('touchmove', this, false);
element.addEventListener('touchend', this, false);
},
move: function(event) {
// ensure swiping with one touch and not pinching
if (event.touches.length > 1 || event.scale && event.scale !== 1) return
if (options.disableScroll) event.preventDefault();
var touches = event.touches[0];
// measure change in x and y
delta = {
x: touches.pageX - start.x,
y: touches.pageY - start.y
}
// determine if scrolling test has run - one time test
if (typeof isScrolling == 'undefined') {
isScrolling = !!(isScrolling || Math.abs(delta.x) < Math.abs(delta.y));
}
// if user is not trying to scroll vertically
if (!isScrolling) {
// prevent native scrolling
event.preventDefault();
// stop slideshow
stop();
// increase resistance if first or last slide
if (options.continuous) { // we don't add resistance at the end
translate(circle(index - 1), delta.x + slidePos[circle(index - 1)], 0);
translate(index, delta.x + slidePos[index], 0);
translate(circle(index + 1), delta.x + slidePos[circle(index + 1)], 0);
} else {
delta.x =
delta.x /
((!index && delta.x > 0 // if first slide and sliding left
||
index == slides.length - 1 // or if last slide and sliding right
&&
delta.x < 0 // and if sliding at all
) ?
(Math.abs(delta.x) / width + 1) // determine resistance level
:
1); // no resistance if false
// translate 1:1
translate(index - 1, delta.x + slidePos[index - 1], 0);
translate(index, delta.x + slidePos[index], 0);
translate(index + 1, delta.x + slidePos[index + 1], 0);
}
}
},
end: function(event) {
// measure duration
var duration = +new Date - start.time;
// determine if slide attempt triggers next/prev slide
var isValidSlide =
Number(duration) < 250 // if slide duration is less than 250ms
&&
Math.abs(delta.x) > 20 // and if slide amt is greater than 20px
||
Math.abs(delta.x) > width / 2; // or if slide amt is greater than half the width
// determine if slide attempt is past start and end
var isPastBounds = !index && delta.x > 0 // if first slide and slide amt is greater than 0
||
index == slides.length - 1 && delta.x < 0; // or if last slide and slide amt is less than 0
if (options.continuous) isPastBounds = false;
// determine direction of swipe (true:right, false:left)
var direction = delta.x < 0;
// if not scrolling vertically
if (!isScrolling) {
if (isValidSlide && !isPastBounds) {
if (direction) {
if (options.continuous) { // we need to get the next in this direction in place
move(circle(index - 1), -width, 0);
move(circle(index + 2), width, 0);
} else {
move(index - 1, -width, 0);
}
move(index, slidePos[index] - width, speed);
move(circle(index + 1), slidePos[circle(index + 1)] - width, speed);
index = circle(index + 1);
} else {
if (options.continuous) { // we need to get the next in this direction in place
move(circle(index + 1), width, 0);
move(circle(index - 2), -width, 0);
} else {
move(index + 1, width, 0);
}
move(index, slidePos[index] + width, speed);
move(circle(index - 1), slidePos[circle(index - 1)] + width, speed);
index = circle(index - 1);
}
options.callback && options.callback(index, slides[index]);
} else {
if (options.continuous) {
move(circle(index - 1), -width, speed);
move(index, 0, speed);
move(circle(index + 1), width, speed);
} else {
move(index - 1, -width, speed);
move(index, 0, speed);
move(index + 1, width, speed);
}
}
}
// kill touchmove and touchend event listeners until touchstart called again
element.removeEventListener('touchmove', events, false)
element.removeEventListener('touchend', events, false)
},
transitionEnd: function(event) {
if (parseInt(event.target.getAttribute('data-index'), 10) == index) {
if (delay) begin();
options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
}
}
}
// trigger setup
setup();
// start auto slideshow if applicable
if (delay) begin();
// add event listeners
if (browser.addEventListener) {
// set touchstart event on element
if (browser.touch) element.addEventListener('touchstart', events, false);
if (browser.transitions) {
element.addEventListener('webkitTransitionEnd', events, false);
element.addEventListener('msTransitionEnd', events, false);
element.addEventListener('oTransitionEnd', events, false);
element.addEventListener('otransitionend', events, false);
element.addEventListener('transitionend', events, false);
}
// set resize event on window
window.addEventListener('resize', events, false);
} else {
window.onresize = function() {
setup()
}; // to play nice with old IE
}
// expose the Swipe API
return {
setup: function() {
setup();
},
slide: function(to, speed) {
// cancel slideshow
stop();
slide(to, speed);
},
prev: function() {
// cancel slideshow
stop();
prev();
},
next: function() {
// cancel slideshow
stop();
next();
},
stop: function() {
// cancel slideshow
stop();
},
getPos: function() {
// return current index position
return index;
},
getNumSlides: function() {
// return total number of slides
return length;
},
kill: function() {
// cancel slideshow
stop();
// reset element
element.style.width = '';
element.style.left = '';
// reset slides
var pos = slides.length;
while (pos--) {
var slide = slides[pos];
slide.style.width = '';
slide.style.left = '';
if (browser.transitions) translate(pos, 0, 0);
}
// removed event listeners
if (browser.addEventListener) {
// remove current event listeners
element.removeEventListener('touchstart', events, false);
element.removeEventListener('webkitTransitionEnd', events, false);
element.removeEventListener('msTransitionEnd', events, false);
element.removeEventListener('oTransitionEnd', events, false);
element.removeEventListener('otransitionend', events, false);
element.removeEventListener('transitionend', events, false);
window.removeEventListener('resize', events, false);
} else {
window.onresize = null;
}
}
}
}
if (window.jQuery || window.Zepto) {
(function($) {
$.fn.Swipe = function(params) {
return this.each(function() {
$(this).data('Swipe', new Swipe($(this)[0], params));
});
}
})(window.jQuery || window.Zepto)
}
ul, li{display: inline-block; list-style:none}
li, .swipeBtn{cursor: pointer}
li+li{margin-left:10px}
li::before {content:'●'; color:grey}
.dot_select::before{color: blue}
#mySwipe{overflow: hidden}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="swipeBtn hotspot hspot cElement" id="prevBtn">❰</div>
<div id='mySwipe' style='width:600px;margin:0 auto' class='swipe hotspot hspot cElement'>
<div class='swipe-wrap'>
<div><span id="slide1">---- SLIDE1 ----</span></div>
<div><span id="slide2">---- SLIDE2 ----</span></div>
<div><span id="slide3">---- SLIDE3 ----</span></div>
</div>
</div>
<div class="swipeBtn hotspot hspot cElement" id="nextBtn">❱</div>
<ul class="swipeDot">
<li class="dot_select"></li>
<li ></li>
<li></li>
</ul>
Added the next lines
prevDot=index;
$(".swipeDot").find("li").eq(index).addClass("dot_select");
This will save the value of the active dot. The second line is yours but i just change the eq(prevdot) to eq(index)
Fior the problem stated in the comments. I debbuged the code and found the error on line 174 of the js.
U had
if (direction !== natural_direction) to= -direction * slides.length + to;
This line changed the value of to before it ended the operation and returned rubbish. So i just changed the to var for newTo and works fine. This is a debbuge of a long script. There might be a better solution but this is the one i got.
Hope this is what you were looking for. Happy to explain or help in a better solution if needed.
var prevDot = 0;
function init() {
var elem = document.getElementById('mySwipe');
window.mySwipe = Swipe(elem, {
// startSlide: 4,
// auto: 3000,
// continuous: true,
// disableScroll: true,
// stopPropagation: true,
// callback: function(index, element) {},
transitionEnd: function(index, element) {
$(".swipeDot").find("li").eq(prevDot).removeClass("dot_select");
prevDot = (index == 0 || index == 2) ? 0 : 1;
prevDot=index; $(".swipeDot").find("li").eq(index).addClass("dot_select");
console.log(index);
}
});
//$(".swipe-wrap").find("div").eq(2).find("span").css({backgroundImage:"url('../images/p006_img_2.png')"})
$("#prevBtn").click(function() {
window.mySwipe.prev();
});
$("#nextBtn").click(function() {
window.mySwipe.next();
});
$(".swipeDot li").each(function(index) {
$(this).attr("slideIndex", index);
});
$(".swipeDot li").click(function() {
var slideIndex = $(this).attr("slideIndex");
window.mySwipe.slide(slideIndex);
});
}
$(document).ready(init);
function Swipe(container, options) {
console.log(container);
"use strict";
// utilities
var noop = function() {}; // simple no operation function
var offloadFn = function(fn) {
setTimeout(fn || noop, 0)
}; // offload a functions execution
// check browser capabilities
var browser = {
addEventListener: !!window.addEventListener,
touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
transitions: (function(temp) {
var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
for (var i in props)
if (temp.style[props[i]] !== undefined) return true;
return false;
})(document.createElement('swipe'))
};
// quit if no root element
if (!container) return;
var element = container.children[0];
var slides, slidePos, width, length;
options = options || {};
var index = parseInt(options.startSlide, 10) || 0;
var speed = options.speed || 300;
options.continuous = options.continuous !== undefined ? options.continuous : true;
function setup() {
// cache slides
slides = element.children;
length = slides.length;
// set continuous to false if only one slide
if (slides.length < 2) options.continuous = false;
//special case if two slides
if (browser.transitions && options.continuous && slides.length < 3) {
element.appendChild(slides[0].cloneNode(true));
element.appendChild(element.children[1].cloneNode(true));
slides = element.children;
}
// create an array to store current positions of each slide
slidePos = new Array(slides.length);
// determine width of each slide
width = container.offsetWidth;
element.style.width = (slides.length * width) + 'px';
// stack elements
var pos = slides.length;
while (pos--) {
var slide = slides[pos];
slide.style.width = width + 'px';
slide.setAttribute('data-index', pos);
if (browser.transitions) {
slide.style.left = (pos * -width) + 'px';
move(pos, index > pos ? -width : (index < pos ? width : 0), 0);
}
}
// reposition elements before and after index
if (options.continuous && browser.transitions) {
move(circle(index - 1), -width, 0);
move(circle(index + 1), width, 0);
}
if (!browser.transitions) element.style.left = (index * -width) + 'px';
container.style.visibility = 'visible';
}
function prev() {
if (options.continuous) slide(index - 1);
else if (index) slide(index - 1);
}
function next() {
if (options.continuous) slide(index + 1);
else if (index < slides.length - 1) slide(index + 1);
}
function circle(index) {
// a simple positive modulo using slides.length
return (slides.length + (index % slides.length)) % slides.length;
}
function slide(to, slideSpeed) {
// do nothing if already on requested slide
if (index == to) return;
if (browser.transitions) {
var direction = Math.abs(index - to) / (index - to); // 1: backward, -1: forward
// get the actual position of the slide
if (options.continuous) {
var natural_direction = direction;
direction = -slidePos[circle(to)] / width;
// if going forward but to < index, use to = slides.length + to
// if going backward but to > index, use to = -slides.length + to
if (direction !== natural_direction) newTo = -direction * slides.length + to;
}
var diff = Math.abs(index - to) - 1;
// move all the slides between index and to in the right direction
while (diff--) move(circle((to > index ? to : index) - diff - 1), width * direction, 0);
to = circle(to);
move(index, width * direction, slideSpeed || speed);
move(to, 0, slideSpeed || speed);
if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place
} else {
to = circle(to);
animate(index * -width, to * -width, slideSpeed || speed);
//no fallback for a circular continuous if the browser does not accept transitions
}
index = to;
offloadFn(options.callback && options.callback(index, slides[index]));
}
function move(index, dist, speed) {
translate(index, dist, speed);
slidePos[index] = dist;
}
function translate(index, dist, speed) {
var slide = slides[index];
var style = slide && slide.style;
if (!style) return;
style.webkitTransitionDuration =
style.MozTransitionDuration =
style.msTransitionDuration =
style.OTransitionDuration =
style.transitionDuration = speed + 'ms';
style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
style.msTransform =
style.MozTransform =
style.OTransform = 'translateX(' + dist + 'px)';
}
function animate(from, to, speed) {
// if not an animation, just reposition
if (!speed) {
element.style.left = to + 'px';
return;
}
var start = +new Date;
var timer = setInterval(function() {
var timeElap = +new Date - start;
if (timeElap > speed) {
element.style.left = to + 'px';
if (delay) begin();
options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
clearInterval(timer);
return;
}
element.style.left = (((to - from) * (Math.floor((timeElap / speed) * 100) / 100)) + from) + 'px';
}, 4);
}
// setup auto slideshow
var delay = options.auto || 0;
var interval;
function begin() {
interval = setTimeout(next, delay);
}
function stop() {
delay = 0;
clearTimeout(interval);
}
// setup initial vars
var start = {};
var delta = {};
var isScrolling;
// setup event capturing
var events = {
handleEvent: function(event) {
switch (event.type) {
case 'touchstart':
this.start(event);
break;
case 'touchmove':
this.move(event);
break;
case 'touchend':
offloadFn(this.end(event));
break;
case 'webkitTransitionEnd':
case 'msTransitionEnd':
case 'oTransitionEnd':
case 'otransitionend':
case 'transitionend':
offloadFn(this.transitionEnd(event));
break;
case 'resize':
offloadFn(setup);
break;
}
if (options.stopPropagation) event.stopPropagation();
},
start: function(event) {
var touches = event.touches[0];
// measure start values
start = {
// get initial touch coords
x: touches.pageX,
y: touches.pageY,
// store time to determine touch duration
time: +new Date
};
// used for testing first move event
isScrolling = undefined;
// reset delta and end measurements
delta = {};
// attach touchmove and touchend listeners
element.addEventListener('touchmove', this, false);
element.addEventListener('touchend', this, false);
},
move: function(event) {
// ensure swiping with one touch and not pinching
if (event.touches.length > 1 || event.scale && event.scale !== 1) return
if (options.disableScroll) event.preventDefault();
var touches = event.touches[0];
// measure change in x and y
delta = {
x: touches.pageX - start.x,
y: touches.pageY - start.y
}
// determine if scrolling test has run - one time test
if (typeof isScrolling == 'undefined') {
isScrolling = !!(isScrolling || Math.abs(delta.x) < Math.abs(delta.y));
}
// if user is not trying to scroll vertically
if (!isScrolling) {
// prevent native scrolling
event.preventDefault();
// stop slideshow
stop();
// increase resistance if first or last slide
if (options.continuous) { // we don't add resistance at the end
translate(circle(index - 1), delta.x + slidePos[circle(index - 1)], 0);
translate(index, delta.x + slidePos[index], 0);
translate(circle(index + 1), delta.x + slidePos[circle(index + 1)], 0);
} else {
delta.x =
delta.x /
((!index && delta.x > 0 // if first slide and sliding left
||
index == slides.length - 1 // or if last slide and sliding right
&&
delta.x < 0 // and if sliding at all
) ?
(Math.abs(delta.x) / width + 1) // determine resistance level
:
1); // no resistance if false
// translate 1:1
translate(index - 1, delta.x + slidePos[index - 1], 0);
translate(index, delta.x + slidePos[index], 0);
translate(index + 1, delta.x + slidePos[index + 1], 0);
}
}
},
end: function(event) {
// measure duration
var duration = +new Date - start.time;
// determine if slide attempt triggers next/prev slide
var isValidSlide =
Number(duration) < 250 // if slide duration is less than 250ms
&&
Math.abs(delta.x) > 20 // and if slide amt is greater than 20px
||
Math.abs(delta.x) > width / 2; // or if slide amt is greater than half the width
// determine if slide attempt is past start and end
var isPastBounds = !index && delta.x > 0 // if first slide and slide amt is greater than 0
||
index == slides.length - 1 && delta.x < 0; // or if last slide and slide amt is less than 0
if (options.continuous) isPastBounds = false;
// determine direction of swipe (true:right, false:left)
var direction = delta.x < 0;
// if not scrolling vertically
if (!isScrolling) {
if (isValidSlide && !isPastBounds) {
if (direction) {
if (options.continuous) { // we need to get the next in this direction in place
move(circle(index - 1), -width, 0);
move(circle(index + 2), width, 0);
} else {
move(index - 1, -width, 0);
}
move(index, slidePos[index] - width, speed);
move(circle(index + 1), slidePos[circle(index + 1)] - width, speed);
index = circle(index + 1);
} else {
if (options.continuous) { // we need to get the next in this direction in place
move(circle(index + 1), width, 0);
move(circle(index - 2), -width, 0);
} else {
move(index + 1, width, 0);
}
move(index, slidePos[index] + width, speed);
move(circle(index - 1), slidePos[circle(index - 1)] + width, speed);
index = circle(index - 1);
}
options.callback && options.callback(index, slides[index]);
} else {
if (options.continuous) {
move(circle(index - 1), -width, speed);
move(index, 0, speed);
move(circle(index + 1), width, speed);
} else {
move(index - 1, -width, speed);
move(index, 0, speed);
move(index + 1, width, speed);
}
}
}
// kill touchmove and touchend event listeners until touchstart called again
element.removeEventListener('touchmove', events, false)
element.removeEventListener('touchend', events, false)
},
transitionEnd: function(event) {
if (parseInt(event.target.getAttribute('data-index'), 10) == index) {
if (delay) begin();
options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
}
}
}
// trigger setup
setup();
// start auto slideshow if applicable
if (delay) begin();
// add event listeners
if (browser.addEventListener) {
// set touchstart event on element
if (browser.touch) element.addEventListener('touchstart', events, false);
if (browser.transitions) {
element.addEventListener('webkitTransitionEnd', events, false);
element.addEventListener('msTransitionEnd', events, false);
element.addEventListener('oTransitionEnd', events, false);
element.addEventListener('otransitionend', events, false);
element.addEventListener('transitionend', events, false);
}
// set resize event on window
window.addEventListener('resize', events, false);
} else {
window.onresize = function() {
setup()
}; // to play nice with old IE
}
// expose the Swipe API
return {
setup: function() {
setup();
},
slide: function(to, speed) {
// cancel slideshow
stop();
slide(to, speed);
},
prev: function() {
// cancel slideshow
stop();
prev();
},
next: function() {
// cancel slideshow
stop();
next();
},
stop: function() {
// cancel slideshow
stop();
},
getPos: function() {
// return current index position
return index;
},
getNumSlides: function() {
// return total number of slides
return length;
},
kill: function() {
// cancel slideshow
stop();
// reset element
element.style.width = '';
element.style.left = '';
// reset slides
var pos = slides.length;
while (pos--) {
var slide = slides[pos];
slide.style.width = '';
slide.style.left = '';
if (browser.transitions) translate(pos, 0, 0);
}
// removed event listeners
if (browser.addEventListener) {
// remove current event listeners
element.removeEventListener('touchstart', events, false);
element.removeEventListener('webkitTransitionEnd', events, false);
element.removeEventListener('msTransitionEnd', events, false);
element.removeEventListener('oTransitionEnd', events, false);
element.removeEventListener('otransitionend', events, false);
element.removeEventListener('transitionend', events, false);
window.removeEventListener('resize', events, false);
} else {
window.onresize = null;
}
}
}
}
if (window.jQuery || window.Zepto) {
(function($) {
$.fn.Swipe = function(params) {
return this.each(function() {
$(this).data('Swipe', new Swipe($(this)[0], params));
});
}
})(window.jQuery || window.Zepto)
}
ul,
li {
display: inline-block;
list-style: none
}
li,
.swipeBtn {
cursor: pointer
}
li+li {
margin-left: 10px
}
li::before {
content: '●';
color: grey
}
.dot_select::before {
color: blue
}
#mySwipe {
overflow: hidden
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="swipeBtn hotspot hspot cElement" id="prevBtn">❰</div>
<div id='mySwipe' style='width:600px;margin:0 auto' class='swipe hotspot hspot cElement'>
<div class='swipe-wrap'>
<div><span id="slide1">---- SLIDE1 ----</span></div>
<div><span id="slide2">---- SLIDE2 ----</span></div>
<div><span id="slide3">---- SLIDE3 ----</span></div>
</div>
</div>
<div class="swipeBtn hotspot hspot cElement" id="nextBtn">❱</div>
<ul class="swipeDot">
<li class="dot_select"></li>
<li></li>
<li></li>
</ul>
You do not need var prevDot. You might play it right using index:
$(".swipeDot li").removeClass("dot_select")
.eq(index).addClass("dot_select");
See the snippet:
function init() {
var elem = document.getElementById('mySwipe');
window.mySwipe = Swipe(elem, {
// startSlide: 4,
// auto: 3000,
// continuous: true,
// disableScroll: true,
// stopPropagation: true,
// callback: function(index, element) {},
transitionEnd: function(index, element) {
$(".swipeDot li").removeClass("dot_select")
.eq(index).addClass("dot_select");
}
});
//$(".swipe-wrap").find("div").eq(2).find("span").css({backgroundImage:"url('../images/p006_img_2.png')"})
$("#prevBtn").click(function() {
window.mySwipe.prev();
});
$("#nextBtn").click(function() {
window.mySwipe.next();
});
$(".swipeDot li").each(function(index) {
$(this).attr("slideIndex", index);
});
$(".swipeDot li").click(function() {
var slideIndex = $(this).attr("slideIndex");
window.mySwipe.slide(slideIndex);
});
}
$(document).ready(init);
function Swipe(container, options) {
console.log(container);
"use strict";
// utilities
var noop = function() {}; // simple no operation function
var offloadFn = function(fn) {
setTimeout(fn || noop, 0)
}; // offload a functions execution
// check browser capabilities
var browser = {
addEventListener: !!window.addEventListener,
touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
transitions: (function(temp) {
var props = ['transitionProperty', 'WebkitTransition', 'MozTransition', 'OTransition', 'msTransition'];
for (var i in props)
if (temp.style[props[i]] !== undefined) return true;
return false;
})(document.createElement('swipe'))
};
// quit if no root element
if (!container) return;
var element = container.children[0];
var slides, slidePos, width, length;
options = options || {};
var index = parseInt(options.startSlide, 10) || 0;
var speed = options.speed || 300;
options.continuous = options.continuous !== undefined ? options.continuous : true;
function setup() {
// cache slides
slides = element.children;
length = slides.length;
// set continuous to false if only one slide
if (slides.length < 2) options.continuous = false;
//special case if two slides
if (browser.transitions && options.continuous && slides.length < 3) {
element.appendChild(slides[0].cloneNode(true));
element.appendChild(element.children[1].cloneNode(true));
slides = element.children;
}
// create an array to store current positions of each slide
slidePos = new Array(slides.length);
// determine width of each slide
width = container.offsetWidth;
element.style.width = (slides.length * width) + 'px';
// stack elements
var pos = slides.length;
while (pos--) {
var slide = slides[pos];
slide.style.width = width + 'px';
slide.setAttribute('data-index', pos);
if (browser.transitions) {
slide.style.left = (pos * -width) + 'px';
move(pos, index > pos ? -width : (index < pos ? width : 0), 0);
}
}
// reposition elements before and after index
if (options.continuous && browser.transitions) {
move(circle(index - 1), -width, 0);
move(circle(index + 1), width, 0);
}
if (!browser.transitions) element.style.left = (index * -width) + 'px';
container.style.visibility = 'visible';
}
function prev() {
if (options.continuous) slide(index - 1);
else if (index) slide(index - 1);
}
function next() {
if (options.continuous) slide(index + 1);
else if (index < slides.length - 1) slide(index + 1);
}
function circle(index) {
// a simple positive modulo using slides.length
return (slides.length + (index % slides.length)) % slides.length;
}
function slide(to, slideSpeed) {
// do nothing if already on requested slide
if (index == to) return;
if (browser.transitions) {
var direction = Math.abs(index - to) / (index - to); // 1: backward, -1: forward
// get the actual position of the slide
if (options.continuous) {
var natural_direction = direction;
direction = -slidePos[circle(to)] / width;
// if going forward but to < index, use to = slides.length + to
// if going backward but to > index, use to = -slides.length + to
if (direction !== natural_direction) to = -direction * slides.length + to;
}
var diff = Math.abs(index - to) - 1;
// move all the slides between index and to in the right direction
while (diff--) move(circle((to > index ? to : index) - diff - 1), width * direction, 0);
to = circle(to);
move(index, width * direction, slideSpeed || speed);
move(to, 0, slideSpeed || speed);
if (options.continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place
} else {
to = circle(to);
animate(index * -width, to * -width, slideSpeed || speed);
//no fallback for a circular continuous if the browser does not accept transitions
}
index = to;
offloadFn(options.callback && options.callback(index, slides[index]));
}
function move(index, dist, speed) {
translate(index, dist, speed);
slidePos[index] = dist;
}
function translate(index, dist, speed) {
var slide = slides[index];
var style = slide && slide.style;
if (!style) return;
style.webkitTransitionDuration =
style.MozTransitionDuration =
style.msTransitionDuration =
style.OTransitionDuration =
style.transitionDuration = speed + 'ms';
style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
style.msTransform =
style.MozTransform =
style.OTransform = 'translateX(' + dist + 'px)';
}
function animate(from, to, speed) {
// if not an animation, just reposition
if (!speed) {
element.style.left = to + 'px';
return;
}
var start = +new Date;
var timer = setInterval(function() {
var timeElap = +new Date - start;
if (timeElap > speed) {
element.style.left = to + 'px';
if (delay) begin();
options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
clearInterval(timer);
return;
}
element.style.left = (((to - from) * (Math.floor((timeElap / speed) * 100) / 100)) + from) + 'px';
}, 4);
}
// setup auto slideshow
var delay = options.auto || 0;
var interval;
function begin() {
interval = setTimeout(next, delay);
}
function stop() {
delay = 0;
clearTimeout(interval);
}
// setup initial vars
var start = {};
var delta = {};
var isScrolling;
// setup event capturing
var events = {
handleEvent: function(event) {
switch (event.type) {
case 'touchstart':
this.start(event);
break;
case 'touchmove':
this.move(event);
break;
case 'touchend':
offloadFn(this.end(event));
break;
case 'webkitTransitionEnd':
case 'msTransitionEnd':
case 'oTransitionEnd':
case 'otransitionend':
case 'transitionend':
offloadFn(this.transitionEnd(event));
break;
case 'resize':
offloadFn(setup);
break;
}
if (options.stopPropagation) event.stopPropagation();
},
start: function(event) {
var touches = event.touches[0];
// measure start values
start = {
// get initial touch coords
x: touches.pageX,
y: touches.pageY,
// store time to determine touch duration
time: +new Date
};
// used for testing first move event
isScrolling = undefined;
// reset delta and end measurements
delta = {};
// attach touchmove and touchend listeners
element.addEventListener('touchmove', this, false);
element.addEventListener('touchend', this, false);
},
move: function(event) {
// ensure swiping with one touch and not pinching
if (event.touches.length > 1 || event.scale && event.scale !== 1) return
if (options.disableScroll) event.preventDefault();
var touches = event.touches[0];
// measure change in x and y
delta = {
x: touches.pageX - start.x,
y: touches.pageY - start.y
}
// determine if scrolling test has run - one time test
if (typeof isScrolling == 'undefined') {
isScrolling = !!(isScrolling || Math.abs(delta.x) < Math.abs(delta.y));
}
// if user is not trying to scroll vertically
if (!isScrolling) {
// prevent native scrolling
event.preventDefault();
// stop slideshow
stop();
// increase resistance if first or last slide
if (options.continuous) { // we don't add resistance at the end
translate(circle(index - 1), delta.x + slidePos[circle(index - 1)], 0);
translate(index, delta.x + slidePos[index], 0);
translate(circle(index + 1), delta.x + slidePos[circle(index + 1)], 0);
} else {
delta.x =
delta.x /
((!index && delta.x > 0 // if first slide and sliding left
||
index == slides.length - 1 // or if last slide and sliding right
&&
delta.x < 0 // and if sliding at all
) ?
(Math.abs(delta.x) / width + 1) // determine resistance level
:
1); // no resistance if false
// translate 1:1
translate(index - 1, delta.x + slidePos[index - 1], 0);
translate(index, delta.x + slidePos[index], 0);
translate(index + 1, delta.x + slidePos[index + 1], 0);
}
}
},
end: function(event) {
// measure duration
var duration = +new Date - start.time;
// determine if slide attempt triggers next/prev slide
var isValidSlide =
Number(duration) < 250 // if slide duration is less than 250ms
&&
Math.abs(delta.x) > 20 // and if slide amt is greater than 20px
||
Math.abs(delta.x) > width / 2; // or if slide amt is greater than half the width
// determine if slide attempt is past start and end
var isPastBounds = !index && delta.x > 0 // if first slide and slide amt is greater than 0
||
index == slides.length - 1 && delta.x < 0; // or if last slide and slide amt is less than 0
if (options.continuous) isPastBounds = false;
// determine direction of swipe (true:right, false:left)
var direction = delta.x < 0;
// if not scrolling vertically
if (!isScrolling) {
if (isValidSlide && !isPastBounds) {
if (direction) {
if (options.continuous) { // we need to get the next in this direction in place
move(circle(index - 1), -width, 0);
move(circle(index + 2), width, 0);
} else {
move(index - 1, -width, 0);
}
move(index, slidePos[index] - width, speed);
move(circle(index + 1), slidePos[circle(index + 1)] - width, speed);
index = circle(index + 1);
} else {
if (options.continuous) { // we need to get the next in this direction in place
move(circle(index + 1), width, 0);
move(circle(index - 2), -width, 0);
} else {
move(index + 1, width, 0);
}
move(index, slidePos[index] + width, speed);
move(circle(index - 1), slidePos[circle(index - 1)] + width, speed);
index = circle(index - 1);
}
options.callback && options.callback(index, slides[index]);
} else {
if (options.continuous) {
move(circle(index - 1), -width, speed);
move(index, 0, speed);
move(circle(index + 1), width, speed);
} else {
move(index - 1, -width, speed);
move(index, 0, speed);
move(index + 1, width, speed);
}
}
}
// kill touchmove and touchend event listeners until touchstart called again
element.removeEventListener('touchmove', events, false)
element.removeEventListener('touchend', events, false)
},
transitionEnd: function(event) {
if (parseInt(event.target.getAttribute('data-index'), 10) == index) {
if (delay) begin();
options.transitionEnd && options.transitionEnd.call(event, index, slides[index]);
}
}
}
// trigger setup
setup();
// start auto slideshow if applicable
if (delay) begin();
// add event listeners
if (browser.addEventListener) {
// set touchstart event on element
if (browser.touch) element.addEventListener('touchstart', events, false);
if (browser.transitions) {
element.addEventListener('webkitTransitionEnd', events, false);
element.addEventListener('msTransitionEnd', events, false);
element.addEventListener('oTransitionEnd', events, false);
element.addEventListener('otransitionend', events, false);
element.addEventListener('transitionend', events, false);
}
// set resize event on window
window.addEventListener('resize', events, false);
} else {
window.onresize = function() {
setup()
}; // to play nice with old IE
}
// expose the Swipe API
return {
setup: function() {
setup();
},
slide: function(to, speed) {
// cancel slideshow
stop();
slide(to, speed);
},
prev: function() {
// cancel slideshow
stop();
prev();
},
next: function() {
// cancel slideshow
stop();
next();
},
stop: function() {
// cancel slideshow
stop();
},
getPos: function() {
// return current index position
return index;
},
getNumSlides: function() {
// return total number of slides
return length;
},
kill: function() {
// cancel slideshow
stop();
// reset element
element.style.width = '';
element.style.left = '';
// reset slides
var pos = slides.length;
while (pos--) {
var slide = slides[pos];
slide.style.width = '';
slide.style.left = '';
if (browser.transitions) translate(pos, 0, 0);
}
// removed event listeners
if (browser.addEventListener) {
// remove current event listeners
element.removeEventListener('touchstart', events, false);
element.removeEventListener('webkitTransitionEnd', events, false);
element.removeEventListener('msTransitionEnd', events, false);
element.removeEventListener('oTransitionEnd', events, false);
element.removeEventListener('otransitionend', events, false);
element.removeEventListener('transitionend', events, false);
window.removeEventListener('resize', events, false);
} else {
window.onresize = null;
}
}
}
}
if (window.jQuery || window.Zepto) {
(function($) {
$.fn.Swipe = function(params) {
return this.each(function() {
$(this).data('Swipe', new Swipe($(this)[0], params));
});
}
})(window.jQuery || window.Zepto)
}
ul,
li {
display: inline-block;
list-style: none
}
li,
.swipeBtn {
cursor: pointer
}
li+li {
margin-left: 10px
}
li::before {
content: '●';
color: grey
}
.dot_select::before {
color: blue
}
#mySwipe {
overflow: hidden
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="swipeBtn hotspot hspot cElement" id="prevBtn">❰</div>
<div id='mySwipe' style='width:600px;margin:0 auto' class='swipe hotspot hspot cElement'>
<div class='swipe-wrap'>
<div><span id="slide1">---- SLIDE1 ----</span></div>
<div><span id="slide2">---- SLIDE2 ----</span></div>
<div><span id="slide3">---- SLIDE3 ----</span></div>
</div>
</div>
<div class="swipeBtn hotspot hspot cElement" id="nextBtn">❱</div>
<ul class="swipeDot">
<li class="dot_select"></li>
<li></li>
<li></li>
</ul>

Trying to initialize FullPage.JS after scrolling through hero

Trying to initiate FullPage.JS after scrolling through hero. Right now if you scroll past the hero - FullPage gets initialized and continues to scroll through the slides with the momentum of the initial scroll. I have this function inplace for my init.
function initFullPage(){
$(".view-case-study").addClass("projects-load");
$(".pagination").addClass("visible");
$(".logo-menu svg").toggleClass("hovered");
$('#fullpage').fullpage({
lazyLoading:false,
navigation: true,
navigationPosition: 'right',
css3:true,
normalScrollElementTouchThreshold: 5,
touchSensitivity: 10,
anchors: a_anchors,
menu: '#myMenu',
normalScrollElements: '.nav, .open-nav, .project-inner, .work-mode, .menu-shelf, .tab, .view-case-study, #hero, .hero-center-container',
afterLoad: function(anchorLink, index){
var loadedSection = $(this);
projectUrl = loadedSection.data('url');
project_title = loadedSection.data('title');
loadedSection.addClass('projects-load');
loadedSection.find(".full-line").animate({'width':'100%'},500);
loadedSection.animate({'background-position-y':'-20px','background-size':'120%'},1000);
$('#hero').animate({'opacity':'0'},1000);
$('#hero').addClass('destroy');
$('.ui-info').animate({'opacity':'1'},350);
},
onLeave: function(index, nextIndex, direction){
var leavingSection = $(this);
leavingSection.removeClass('projects-load');
leavingSection.find(".full-line").animate({'width':'0%'},250);
leavingSection.animate({'background-position-y':'0px','background-size':'110%'},100);
$('#project-inner-container').animate({scrollTop:0},0);
$('.ui-info').animate({'opacity':'0'},0);
}
});
fullPageInit = true;
}
Below is my Hero scroll script. I've tried to initialize the script and silentmove to the first section but it doesn't want to listen.
var winHeight = $(window).height();
$(window).scroll(function () {
var scrTop = $(document).scrollTop() / winHeight,
scrTopFixed = scrTop.toFixed(2),
scrTransform = scrTopFixed * 80,
bgPos = scrTransform / 10 + 95,
heroOpacity = 1 - scrTransform / 100;
if ((scrTransform >= 80) && (fullPageInit == false)) {
initFullPage();
$.fn.fullpage.silentMoveTo('#sidepocket');
}
$('svg.scroll-end').css({
'clip': "rect(0px," + scrTransform + "px,200px,0px)",
});
}); // Close
// Scroll SVG Hero
$('#scroll-control').on('scroll',function(e){
var totalScroll = $('#scroll-control').scrollTop();
var slowScroll = totalScroll * .2;
console.log(slowScroll);
$('svg.scroll-end').css({
'clip': "rect(0px," + slowScroll + "px,200px,0px)",
});
if(totalScroll > 400){
if((fullPageInit == false) && (workPage == false)){
fullPageInit = true;
$('#hero').animate({'opacity':'0'},300,function(){
// remove scroll listener
$('#scroll-control').off();
// set first project DOM
var wh = window.innerHeight ? window.innerHeight:$(window).height();
$('#fullpage section').height(wh);
var loadedSection = $('#fullpage section:first-child');
projectUrl = loadedSection.data('url');
project_title = loadedSection.data('title');
loadedSection.addClass('projects-load');
loadedSection.find(".full-line").animate({'width':'100%'},500);
history.pushState(null, null, '#'+projectUrl);
loadedSection.animate({'background-position-y':'-20px','background-size':'120%'},1000,function(){
initFullPage();
$('#scroll-control').hide();
});
$('.ui-info').animate({'opacity':'1'},350);
});
$('#hero').addClass('destroy');
}
}
});
var winHeight = $(window).height();
$(window).scroll(function (e) {
console.log(e);
var scrTop = $(document).scrollTop() / winHeight,
scrTopFixed = scrTop.toFixed(2),
scrTransform = scrTopFixed * 80,
bgPos = scrTransform / 10 + 95,
heroOpacity = 1 - scrTransform / 100;
if ((scrTransform >= 80) && (fullPageInit === false)) {
}
}); // Close
The issue was fixed by setting a time out so that FullPage doesn't initialize until the scrolling of the mouse ends, therefore you do not overscroll or have any momentum that forces the user to the next section.
Hope this helps others trying to build custom scripts into FullPage.JS
https://www.alexcoven.com

fadeIn and fadeOut functions not working

I am working on fadein and fadeout functions using pure javascript, here is the code:
(function() {
var fx = {
easing: {
linear: function(progress) {
return progress;
},
quadratic: function(progress) {
return Math.pow(progress, 2);
},
swing: function(progress) {
return 0.5 - Math.cos(progress * Math.PI) / 2;
},
circ: function(progress) {
return 1 - Math.sin(Math.acos(progress));
},
back: function(progress, x) {
return Math.pow(progress, 2) * ((x + 1) * progress - x);
},
bounce: function(progress) {
for (var a = 0, b = 1, result; 1; a += b, b /= 2) {
if (progress >= (7 - 4 * a) / 11) {
return -Math.pow((11 - 6 * a - 11 * progress) / 4, 2) + Math.pow(b, 2);
}
}
},
elastic: function(progress, x) {
return Math.pow(2, 10 * (progress - 1)) * Math.cos(20 * Math.PI * x / 3 * progress);
}
},
animate: function(options) {
var start = new Date;
var id = setInterval(function() {
var timePassed = new Date - start;
var progress = timePassed / options.duration;
if (progress > 1) {
progress = 1;
}
options.progress = progress;
var delta = options.delta(progress);
options.step(delta);
if (progress == 1) {
clearInterval(id);
options.complete();
}
}, options.delay || 10);
},
fadeOut: function(element, options) {
var to = 1;
this.animate({
duration: options.duration,
delta: function(progress) {
progress = this.progress;
return fx.easing.swing(progress);
},
complete: options.complete,
step: function(delta) {
element.style.opacity = to - delta;
}
});
},
fadeIn: function(element, options) {
var to = 0;
this.animate({
duration: options.duration,
delta: function(progress) {
progress = this.progress;
return fx.easing.swing(progress);
},
complete: options.complete,
step: function(delta) {
element.style.opacity = to + delta;
}
});
}
};
window.fx = fx;
})()
I am using the following code to activate the function:
document.getElementById('in').addEventListener('click', function() {
FX.fadeIn(document.getElementById('type'), {
duration: 2000,
});
}, false);
But when I load the page I get an error with the activation code.
Does anyone know what I have done wrong?
Thank you so much.
With a few adjustments, your code should work fine...
As Richard Dalton noticed, call the object with fx not FX.
Add default values for all options in case an option isn't provided (your example code throws an error because options.complete is undefined). Example:
this.animate({
duration: options.duration || 1000,
...
complete: options.complete || function() { },
...
});
Adjust the styles before animating (imagine an element is hidden using display: none instead of opacity: 0)... Example (for fadeIn):
element.style.opacity = 0;
element.style.visibility = "visible";
element.style.display = "block";
Check if an action is needed at all (e.g. call to fadeIn despite element already being visible):
isVisible: function(element) {
return element.style.display !== "none" &&
element.style.visibility !== "hidden" &&
element.style.opacity !== "0";
}
// In fadeIn:
if (!this.isVisible(element)) {
...
}
Here's the corrected code with an example: JSFiddle
Certainly one could tweak this a little further, deal with some corner cases (e.g. what happens if there is a call to fadeIn while the element is currently being faded out?), and I'm pretty sure it doesn't work in all browsers (old IEs)... But I hope I pointed you in the right direction. :)

Jquery custom slider infinite loop

I did jquery slider using this tutorial
http://css-plus.com/2010/09/create-your-own-jquery-image-slider/
, where the pictures are sliding automatically, but just once. How can I make them circle in an infinite loop?
on-line example :
www.vytvarkajablonec.jecool.net/ati
I'd really appreciate your help!
Replace the JS code from tutorial for this:
$(document).ready(function () {
// Gallery
if (jQuery("#gallery").length) {
// Declare variables
var totalImages = jQuery("#gallery > li").length,
imageWidth = jQuery("#gallery > li:first").outerWidth(true),
totalWidth = imageWidth * totalImages,
visibleImages = Math.round(jQuery("#gallery-wrap").width() / imageWidth),
visibleWidth = visibleImages * imageWidth,
stopPosition = (visibleWidth - totalWidth);
jQuery("#gallery").width(totalWidth);
jQuery("#gallery-prev").click(function () {
if (jQuery("#gallery").position().left < 0 && !jQuery("#gallery").is(":animated")) {
jQuery("#gallery").animate({
left: "+=" + imageWidth + "px"
});
}
if (jQuery("#gallery").position().left === 0) {
jQuery("#gallery > li:last").prependTo($("#gallery"));
}
return false;
});
jQuery("#gallery-next").click(function () {
if (jQuery("#gallery").position().left > stopPosition && !jQuery("#gallery").is(":animated")) {
jQuery("#gallery").animate({
left: "-=" + imageWidth + "px"
});
}
if (jQuery("#gallery").position().left === stopPosition) {
jQuery("#gallery > li:first").appendTo($("#gallery"));
}
return false;
});
}
});
Just animate the gallary back to it's initial position if it is at the end of the gallary.
var oGallary = $('#gallery');
var gallarWidth = oGallary.width();
if(oGalary.position().left > stopPosition && oGallary.is(":animated") == false)
{
oGallary.animate({left : "-=" + imageWidth + "px"});
}
else if ( oGalary.position().left <= stopPosition && oGallary.is(":animated") == false )
{
oGallary.animate({left : "+=" + gallaryWidht + "px"}) // Get full length of the entire gallary
}

call javascript / jQuery function

I am using the following javascript which uses some jQuery, neither of which I know much about. This is for a simple image slider:
/*!
* jQuery wmuSlider v2.1
*
* Copyright (c) 2011 Brice Lechatellier
* http://brice.lechatellier.com/
*
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/
;(function($) {
$.fn.wmuSlider = function(options) {
/* Default Options
================================================== */
var defaults = {
animation: 'fade',
animationDuration: 600,
slideshow: true,
slideshowSpeed: 7000,
slideToStart: 0,
navigationControl: true,
paginationControl: true,
previousText: 'Previous',
nextText: 'Next',
touch: false,
slide: 'article',
items: 1
};
var options = $.extend(defaults, options);
return this.each(function() {
/* Variables
================================================== */
var $this = $(this);
var currentIndex = options.slideToStart;
var wrapper = $this.find('.wmuSliderWrapper');
var slides = $this.find(options.slide);
var slidesCount = slides.length;
var slideshowTimeout;
var paginationControl;
var isAnimating;
/* Load Slide
================================================== */
var loadSlide = function(index, infinite, touch) {
if (isAnimating) {
return false;
}
isAnimating = true;
currentIndex = index;
var slide = $(slides[index]);
$this.animate({ height: slide.innerHeight() });
if (options.animation == 'fade') {
slides.css({
position: 'absolute',
opacity: 0
});
slide.css('position', 'relative');
slide.animate({ opacity:1 }, options.animationDuration, function() {
isAnimating = false;
});
} else if (options.animation == 'slide') {
if (!infinite) {
wrapper.animate({ marginLeft: -$this.width() / options.items * index }, options.animationDuration, function() {
isAnimating = false;
});
} else {
if (index == 0) {
wrapper.animate({ marginLeft: -$this.width() / options.items * slidesCount }, options.animationDuration, function() {
wrapper.css('marginLeft', 0);
isAnimating = false;
});
} else {
if (!touch) {
wrapper.css('marginLeft', -$this.width() / options.items * slidesCount);
}
wrapper.animate({ marginLeft: -$this.width() / options.items * index }, options.animationDuration, function() {
isAnimating = false;
});
}
}
}
if (paginationControl) {
paginationControl.find('a').each(function(i) {
if(i == index) {
$(this).addClass('wmuActive');
} else {
$(this).removeClass('wmuActive');
}
});
}
// Trigger Event
$this.trigger('slideLoaded', index);
};
/* Navigation Control
================================================== */
if (options.navigationControl) {
var prev = $('<a class="wmuSliderPrev">' + options.previousText + '</a>');
prev.click(function(e) {
e.preventDefault();
clearTimeout(slideshowTimeout);
if (currentIndex == 0) {
loadSlide(slidesCount - 1, true);
} else {
loadSlide(currentIndex - 1);
}
});
$this.append(prev);
var next = $('<a class="wmuSliderNext">' + options.nextText + '</a>');
next.click(function(e) {
e.preventDefault();
clearTimeout(slideshowTimeout);
if (currentIndex + 1 == slidesCount) {
loadSlide(0, true);
} else {
loadSlide(currentIndex + 1);
}
});
$this.append(next);
}
/* Pagination Control
================================================== */
if (options.paginationControl) {
paginationControl = $('<ul class="wmuSliderPagination"></ul>');
$.each(slides, function(i) {
paginationControl.append('<li>' + i + '</li>');
paginationControl.find('a:eq(' + i + ')').click(function(e) {
e.preventDefault();
clearTimeout(slideshowTimeout);
loadSlide(i);
});
});
$this.append(paginationControl);
}
/* Slideshow
================================================== */
if (options.slideshow) {
var slideshow = function() {
if (currentIndex + 1 < slidesCount) {
loadSlide(currentIndex + 1);
} else {
loadSlide(0, true);
}
slideshowTimeout = setTimeout(slideshow, options.slideshowSpeed);
}
slideshowTimeout = setTimeout(slideshow, options.slideshowSpeed);
}
/* Resize Slider
================================================== */
var resize = function() {
var slide = $(slides[currentIndex]);
$this.animate({ height: slide.innerHeight() });
if (options.animation == 'slide') {
slides.css({
width: $this.width() / options.items
});
wrapper.css({
marginLeft: -$this.width() / options.items * currentIndex,
width: $this.width() * slides.length
});
}
};
/* Touch
================================================== */
var touchSwipe = function(event, phase, direction, distance) {
clearTimeout(slideshowTimeout);
if(phase == 'move' && (direction == 'left' || direction == 'right')) {
if (direction == 'right') {
if (currentIndex == 0) {
wrapper.css('marginLeft', (-slidesCount * $this.width() / options.items) + distance);
} else {
wrapper.css('marginLeft', (-currentIndex * $this.width() / options.items) + distance);
}
} else if (direction == 'left') {
wrapper.css('marginLeft', (-currentIndex * $this.width() / options.items) - distance);
}
} else if (phase == 'cancel' ) {
if (direction == 'right' && currentIndex == 0) {
wrapper.animate({ marginLeft: -slidesCount * $this.width() / options.items }, options.animationDuration);
} else {
wrapper.animate({ marginLeft: -currentIndex * $this.width() / options.items }, options.animationDuration);
}
} else if (phase == 'end' ) {
if (direction == 'right') {
if (currentIndex == 0) {
loadSlide(slidesCount - 1, true, true);
} else {
loadSlide(currentIndex - 1);
}
} else if (direction == 'left') {
if (currentIndex + 1 == slidesCount) {
loadSlide(0, true);
} else {
loadSlide(currentIndex + 1);
}
} else {
wrapper.animate({ marginLeft: -currentIndex * $this.width() / options.items }, options.animationDuration);
}
}
};
if (options.touch && options.animation == 'slide') {
if (!$.isFunction($.fn.swipe)) {
$.ajax({
url: 'jquery.touchSwipe.min.js',
async: false
});
}
if ($.isFunction($.fn.swipe)) {
$this.swipe({ triggerOnTouchEnd:false, swipeStatus:touchSwipe, allowPageScroll:'vertical' });
}
}
/* Init Slider
================================================== */
var init = function() {
var slide = $(slides[currentIndex]);
var img = slide.find('img');
img.load(function() {
wrapper.show();
$this.animate({ height: slide.innerHeight() });
});
if (options.animation == 'fade') {
slides.css({
position: 'absolute',
width: '100%',
opacity: 0
});
$(slides[currentIndex]).css('position', 'relative');
} else if (options.animation == 'slide') {
if (options.items > slidesCount) {
options.items = slidesCount;
}
slides.css('float', 'left');
slides.each(function(i){
var slide = $(this);
slide.attr('data-index', i);
});
for(var i = 0; i < options.items; i++) {
wrapper.append($(slides[i]).clone());
}
slides = $this.find(options.slide);
}
resize();
$this.trigger('hasLoaded');
loadSlide(currentIndex);
}
init();
/* Bind Events
================================================== */
// Resize
$(window).resize(resize);
// Load Slide
$this.bind('loadSlide', function(e, i) {
clearTimeout(slideshowTimeout);
loadSlide(i);
});
});
}
})(jQuery);
what I want to be able to do is change the slider image index with some sort of 'onclick' event. for example:
<img src="images/IMG_5137_s.jpg" width="100%" />
this however does not call the 'loadslide' function in the javascript file, probably because I don't know what I'm doing.... any help with this would be appreciated.
You can inspect this answer for jQuery plugin-authoring:
How to create simple jQuery plugin?
And here is the simple jsFiddle example with explanation on it.

Categories