Moving a Div on Mouse Move - javascript

I have jquery code that triggers the div to move on movement on a mouse wheel.
The code below works on mouse wheel movement.
What i am trying to implement is that i want the div to move when the mouse is moved to the left or right of the screen?
function scrollLeft() {
var $left = Math.abs(Number($galleryList.css("margin-left").replace("px", "")))
;
if ($left - itemWidth <= 0) {
$galleryList.css({"margin-left": ""});
}
else {
$galleryList.css({"margin-left": -1 * Number($left - itemWidth) + "px"});
}
$(document).trigger("mousemove");
}
function scrollRight() {
var $left = Math.abs(Number($galleryList.css("margin-left").replace("px", "")))
;
if ($galleryList.width() < itemWidth + $left + $window.width()) {
$galleryList.css({"margin-left": -1 * Number($galleryList.width() - $window.width()) + "px"});
}
else {
$galleryList.css({"margin-left": -1 * Number($left + itemWidth) + "px"});
}
$(document).trigger("mousemove");
}
$window.on("mousewheel", function (event) {
if (stackedMode) {
return true;
}
if (event.deltaY == 1) { // left
scrollLeft();
}
else if (event.deltaY == -1) { // right
scrollRight();
}
animating = true;
setTimeout(function () {
animating = false;
}, 500);
})

Related

How to prevent click while scrolling horizontally

I am using cards list with links and it is scrollable horizontally using mouse as well as arrows.
I Want to prevent clicking ( tags) while scrolling/dragging items left or right.
But clicking should work if i am not dragging items.
Here is what I am using in Javascript.
Code
var instance = $(".hs__wrapper");
$.each( instance, function(key, value)
{
var arrows = $(instance[key]).find(".arrow"),
prevArrow = arrows.filter('.arrow-prev'),
nextArrow = arrows.filter('.arrow-next'),
box = $(instance[key]).find(".hs"),
x = 0,
mx = 0,
maxScrollWidth = box[0].scrollWidth - (box[0].clientWidth / 2) - (box.width() / 2);
$(arrows).on('click', function() {
if ($(this).hasClass("arrow-next")) {
x = ((box.width() / 2)) + box.scrollLeft() - 10;
box.animate({
scrollLeft: x,
})
} else {
x = ((box.width() / 2)) - box.scrollLeft() -10;
box.animate({
scrollLeft: -x,
})
}
});
$(box).on({
mousemove: function(e) {
var mx2 = e.pageX - this.offsetLeft;
if(mx) this.scrollLeft = this.sx + mx - mx2;
},
mousedown: function(e) {
this.sx = this.scrollLeft;
mx = e.pageX - this.offsetLeft;
},
scroll: function() {
toggleArrows();
}
});
$(document).on("mouseup", function(){
mx = 0;
});
function toggleArrows() {
if(box.scrollLeft() > maxScrollWidth - 10) {
// disable next button when right end has reached
nextArrow.addClass('disabled');
} else if(box.scrollLeft() < 10) {
// disable prev button when left end has reached
prevArrow.addClass('disabled')
} else{
// both are enabled
nextArrow.removeClass('disabled');
prevArrow.removeClass('disabled');
}
}
});
Try adding a click event handler to the links which prevents default browser behaviour while scrolling. Then, remove the event handler, detecting when scrolling stops using e.g. this method.
var instance = $(".hs__wrapper");
$.each( instance, function(key, value)
{
var arrows = $(instance[key]).find(".arrow"),
prevArrow = arrows.filter('.arrow-prev'),
nextArrow = arrows.filter('.arrow-next'),
box = $(instance[key]).find(".hs"),
x = 0,
mx = 0,
maxScrollWidth = box[0].scrollWidth - (box[0].clientWidth / 2) - (box.width() / 2);
$(arrows).on('click', function() {
if ($(this).hasClass("arrow-next")) {
x = ((box.width() / 2)) + box.scrollLeft() - 10;
box.animate({
scrollLeft: x,
})
} else {
x = ((box.width() / 2)) - box.scrollLeft() -10;
box.animate({
scrollLeft: -x,
})
}
});
$(box).on({
mousemove: function(e) {
var mx2 = e.pageX - this.offsetLeft;
if(mx) this.scrollLeft = this.sx + mx - mx2;
},
mousedown: function(e) {
this.sx = this.scrollLeft;
mx = e.pageX - this.offsetLeft;
},
scroll: function() {
clearTimeout($.data(this, 'scrollTimer'));
$.data(this, 'scrollTimer', setTimeout(function() {
$(box).find('a').off('click');
}, 250));
toggleArrows();
$(box).find('a').on('click', function(e) {
e.preventDefault();
});
}
});
$(document).on("mouseup", function(){
mx = 0;
});
function toggleArrows() {
if(box.scrollLeft() > maxScrollWidth - 10) {
// disable next button when right end has reached
nextArrow.addClass('disabled');
} else if(box.scrollLeft() < 10) {
// disable prev button when left end has reached
prevArrow.addClass('disabled')
} else{
// both are enabled
nextArrow.removeClass('disabled');
prevArrow.removeClass('disabled');
}
}
});

How to prevent draggable handles in range slider form overlapping?

I have to prevent dragable handles in range slider form overlapping . It is vanilla js plugin.
I tried to disable updating offset if the difference between two handles position is lower than 20px. It works sometimes, but the barrier is not precise. The movement is choppy when the handles are near to each other.The handle cannot be dragged immediately, but after few movements.
Here are the fragments of the plugin code:
// HELPERS
// map slider range to value range
Number.prototype.map = function(in_min, in_max, out_min, out_max) {
return (this - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
// round to nearest multiple
Number.prototype.roundTo = function(num) {
var resto = this % num;
if (resto <= (num / 2)) {
return this - resto;
} else {
return this + num - resto;
}
}
//EVENTS
var EVmove = ('ontouchstart' in document.documentElement) ? 'touchmove' : 'mousemove',
EVmove = ('ontouchstart' in document.documentElement) ? 'touchmove' : 'mousemove',
EVend = ('ontouchstart' in document.documentElement) ? 'touchend' : 'mouseup';
document.addEventListener(EVmove, actions.move, false);
document.addEventListener(EVend, function() {
return movebar = false;
}, false);
document.addEventListener(EVstart, function() {
return movebar = true;
}, false);
var movebar = true;
// MOVE HANDLE
actions.move = function(event) {
var clientX = ('ontouchstart' in document.documentElement) ? event.touches[0].clientX : event.clientX;
leftOffset = clientX - posX;
// move handle bar
if (movebar) {
element.style.left = leftOffset + "px";
var v = leftOffset.map(0, elWidth, 0, window.range); // 0
var value = v.roundTo(step);
output.innerHTML = value.toFixed(2);
// prevent handles ovelaping
if (vsOpts.range) {
var diff = Math.abs(parseInt(handle1.offsetLeft) - parseInt(handle2.offsetLeft));
if (diff < 20) {
movebar = false;
}
}
}
}
I solved it by assigning position of the opposite handle as a limit position of the current handle
document.addEventListener(EVstart, function(event) {
if (event.target.id == "vslider-handle1") {
useHandle1 = true
} else {
useHandle1 = false
}
return movebar = true;
}, false);
}
handle1Limit=parseInt(handle2.offsetLeft);
handle2Limit=parseInt(handle1.offsetLeft);
handle1Pos= parseInt(handle1.offsetLeft);
handle2Pos= parseInt(handle2.offsetLeft);
if(useHandle1){
if(handle1Pos>=handle1Limit){
handle1.style.left = handle1Limit + "px";
handle2.style.left = handle1Limit + "px";
}
}
else{
if(handle2Pos<=handle2Limit){
handle2.style.left = handle2Limit + "px";
handle1.style.left = handle2Limit + "px";
}
}

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>

Make HTML5 draggable items scroll the page?

I'm using the HTML5 attribute draggable = "true" on some of my divs on my webpage. I want it so that when you drag one of these items to the bottom of the page, it scrolls the page down and when you drag it to the top, it scrolls the page up.
I will eventually make a playlist on my sidebar, and since it will not always be on view depending on where you're looking on the page, the page needs to scroll when you're dragging.
My page is here and you can try dragging the pictures of the posts around. On Chrome, it automatically lets me scroll down when I drag to the bottom, but not up. On Firefox, it doesn't automatically let me scroll either direction. Any help?
Here's a simple jsfiddle to get you started. On Chrome you should be able to drag the Google icon down and have it scroll the page down, but not going up.
here is a code that will scroll-up or scroll-down your page while you are dragging something. Just placing your dragging object at top or bottom of the page. :)
var stop = true;
$(".draggable").on("drag", function (e) {
stop = true;
if (e.originalEvent.clientY < 150) {
stop = false;
scroll(-1)
}
if (e.originalEvent.clientY > ($(window).height() - 150)) {
stop = false;
scroll(1)
}
});
$(".draggable").on("dragend", function (e) {
stop = true;
});
var scroll = function (step) {
var scrollY = $(window).scrollTop();
$(window).scrollTop(scrollY + step);
if (!stop) {
setTimeout(function () { scroll(step) }, 20);
}
}
I have made a simple JavaScript drag and drop class. It can automatically scroll up or down the page while dragging.
See this jsfiddle. Also avaliable at my github page.
Dragging at a high speed is not recommended now. I need to work out that.
Code below is a part of the library.
var autoscroll = function (offset, poffset, parentNode) {
var xb = 0;
var yb = 0;
if (poffset.isBody == true) {
var scrollLeft = poffset.scrollLeft;
var scrollTop = poffset.scrollTop;
var scrollbarwidth = (document.documentElement.clientWidth - document.body.offsetWidth); //All
var scrollspeed = (offset.right + xb) - (poffset.right + scrollbarwidth);
if (scrollspeed > 0) {
this.scrollLeft(parentNode, scrollLeft + scrollspeed);
}
scrollspeed = offset.left - (xb);
if (scrollspeed < 0) {
this.scrollLeft(parentNode, scrollLeft + scrollspeed);
}
scrollspeed = (offset.bottom + yb) - (poffset.bottom);
if (scrollspeed > 0) {
this.scrollTop(parentNode, scrollTop + scrollspeed);
}
scrollspeed = offset.top - (yb);
if (scrollspeed < 0) {
this.scrollTop(parentNode, scrollTop + scrollspeed);
}
} else {
var scrollLeft = offset.scrollLeft;
var scrollTop = offset.scrollTop;
var scrollbarwidth = parentNode.offsetWidth - parentNode.clientWidth; //17
var scrollbarheight = parentNode.offsetHeight - parentNode.clientHeight; //17
var scrollspeed = (offset.right + xb) - (poffset.right - scrollbarwidth);
if (scrollspeed > 0) {
this.scrollLeft(parentNode, scrollLeft + scrollspeed);
}
scrollspeed = offset.left - (xb + poffset.left);
if (scrollspeed < 0) {
this.scrollLeft(parentNode, scrollLeft + scrollspeed);
}
scrollspeed = (offset.bottom + scrollbarheight + yb) - (poffset.bottom);
if (scrollspeed > 0) {
this.scrollTop(parentNode, scrollTop + scrollspeed);
}
scrollspeed = offset.top - (yb + poffset.top);
if (scrollspeed < 0) {
this.scrollTop(parentNode, scrollTop + scrollspeed);
}
}
};
Here is the javascript version of AngularPlayers answer, I added horizontal support. I noticed both the JQuery solution and Javascript solution have a bug on mobile safari that allows the page to infinitely grow when the bounce effect from overscrolling happens.
The purpose of VerticalMaxed and HorizontalMaxed is to check that the scroll bars are not maxed before scrolling again. This prevents the page from growing during overscroll bounce.
var stopX = true;
var stopY = true;
document.addEventListener('drag', function(e) {
if (event.target.classList.contains('draggable')) {
stopY = true;
// Handle Y
if (e.clientY < 150) {
stopY = false;
scroll(0,-1)
}
if ((e.clientY > ( document.documentElement.clientHeight - 150)) && !VerticalMaxed()) {
stopY = false;
scroll(0,1)
}
// Handle X
stopX = true;
if (e.clientX < 150) {
stopX = false;
scroll(-1,0)
}
if ((e.clientX > ( document.documentElement.clientWidth - 150)) && !HorizontalMaxed()) {
stopX = false;
scroll(1,0)
}
}
});
document.addEventListener('dragend', function(e) {
if (event.target.classList.contains('draggable')) {
stopY = true;
//stopY = true;
stopX = true;
}
});
// On drag scroll, prevents page from growing with mobile safari rubber-band effect
var VerticalMaxed = function(){ return (window.innerHeight + window.scrollY) >= document.body.offsetHeight}
var HorizontalMaxed = function(){ return (window.pageXOffset) > (document.body.scrollWidth - document.body.clientWidth);}
var scroll = function (stepX, stepY) {
var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
window.scrollTo((scrollX + stepX), (scrollY + stepY));
if (!stopY || !stopX) {
setTimeout(function () { scroll(stepX, stepY) }, 20);
}
}

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
}

Categories