stopping anchor scrolling on key press using smoothscroll.js - anchor

I'm trying to get a nice easing scroll effect on my site using smoothscroll.js from http://cferdinandi.github.io/smooth-scroll/ (shown as code below) and it works fine. However, scrolling with mousewheel while that's in effect causes the page to jitter all over the place because there are two animations taking place - the one from the the mousewheel and the other from the anchor scroll. So I'd like to either disable mousewheel on the anchor scroll animation or disable the anchor scroll animation on mousewheel. I'm not sure how to alter the code to do that. I'm pretty sure I should just be able to add a line or two to the code below but I've been trying for many hours and I can't get anything to work.
/* =============================================================
Smooth Scroll 3.2
Animate scrolling to anchor links, by Chris Ferdinandi.
http://gomakethings.com
Easing support contributed by Willem Liu.
https://github.com/willemliu
Easing functions forked from Gaëtan Renaudeau.
https://gist.github.com/gre/1650294
URL history support contributed by Robert Pate.
https://github.com/robertpateii
Fixed header support contributed by Arndt von Lucadou.
https://github.com/a-v-l
Infinite loop bugs in iOS and Chrome (when zoomed) by Alex Guzman.
https://github.com/alexguzman
Free to use under the MIT License.
http://gomakethings.com/mit/
* ============================================================= */
window.smoothScroll = (function (window, document, undefined) {
'use strict';
// Feature Test
if ( 'querySelector' in document && 'addEventListener' in window && Array.prototype.forEach ) {
// SELECTORS
var scrollToggles = document.querySelectorAll('[data-scroll]');
// METHODS
// Run the smooth scroll animation
var runSmoothScroll = function (anchor, duration, easing, url) {
// SELECTORS
var startLocation = window.pageYOffset;
// Get the height of a fixed header if one exists
var scrollHeader = document.querySelector('[data-scroll-header]');
var headerHeight = scrollHeader === null ? 0 : scrollHeader.offsetHeight;
// Set the animation variables to 0/undefined.
var timeLapsed = 0;
var percentage, position;
// METHODS
// Calculate the easing pattern
var easingPattern = function (type, time) {
if ( type == 'easeInQuad' ) return time * time; // accelerating from zero velocity
if ( type == 'easeOutQuad' ) return time * (2 - time); // decelerating to zero velocity
if ( type == 'easeInOutQuad' ) return time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration
if ( type == 'easeInCubic' ) return time * time * time; // accelerating from zero velocity
if ( type == 'easeOutCubic' ) return (--time) * time * time + 1; // decelerating to zero velocity
if ( type == 'easeInOutCubic' ) return time < 0.5 ? 4 * time * time * time : (time - 1) * (2 * time - 2) * (2 * time - 2) + 1; // acceleration until halfway, then deceleration
if ( type == 'easeInQuart' ) return time * time * time * time; // accelerating from zero velocity
if ( type == 'easeOutQuart' ) return 1 - (--time) * time * time * time; // decelerating to zero velocity
if ( type == 'easeInOutQuart' ) return time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration
if ( type == 'easeInQuint' ) return time * time * time * time * time; // accelerating from zero velocity
if ( type == 'easeOutQuint' ) return 1 + (--time) * time * time * time * time; // decelerating to zero velocity
if ( type == 'easeInOutQuint' ) return time < 0.5 ? 16 * time * time * time * time * time : 1 + 16 * (--time) * time * time * time * time; // acceleration until halfway, then deceleration
return time; // no easing, no acceleration
};
// Update the URL
var updateURL = function (url, anchor) {
if ( url === 'true' && history.pushState ) {
history.pushState( {pos:anchor.id}, '', '#' + anchor.id );
}
};
// Calculate how far to scroll
var getEndLocation = function (anchor) {
var location = 0;
if (anchor.offsetParent) {
do {
location += anchor.offsetTop;
anchor = anchor.offsetParent;
} while (anchor);
}
location = location - headerHeight;
if ( location >= 0 ) {
return location;
} else {
return 0;
}
};
var endLocation = getEndLocation(anchor);
var distance = endLocation - startLocation;
// Stop the scrolling animation when the anchor is reached (or at the top/bottom of the page)
var stopAnimation = function () {
var currentLocation = window.pageYOffset;
if ( position == endLocation || currentLocation == endLocation || ( (window.innerHeight + currentLocation) >= document.body.scrollHeight ) ) {
clearInterval(runAnimation);
}
};
// Scroll the page by an increment, and check if it's time to stop
var animateScroll = function () {
timeLapsed += 16;
percentage = ( timeLapsed / duration );
percentage = ( percentage > 1 ) ? 1 : percentage;
position = startLocation + ( distance * easingPattern(easing, percentage) );
window.scrollTo( 0, position );
stopAnimation();
};
// EVENTS, LISTENERS, AND INITS
updateURL(url, anchor);
var runAnimation = setInterval(animateScroll, 16);
};
// Check that anchor exists and run scroll animation
var handleToggleClick = function (event) {
// SELECTORS
// Get anchor link and calculate distance from the top
var dataID = this.getAttribute('href');
var dataTarget = document.querySelector(dataID);
var dataSpeed = this.getAttribute('data-speed');
var dataEasing = this.getAttribute('data-easing');
var dataURL = this.getAttribute('data-url');
// EVENTS, LISTENERS, AND INITS
event.preventDefault();
if (dataTarget) {
runSmoothScroll( dataTarget, dataSpeed || 500, dataEasing || 'easeInOutCubic', dataURL || 'false' );
}
};
// EVENTS, LISTENERS, AND INITS
// When a toggle is clicked, run the click handler
Array.prototype.forEach.call(scrollToggles, function (toggle, index) {
toggle.addEventListener('click', handleToggleClick, false);
});
// Return to the top of the page when back button is clicked and no hash is set
window.onpopstate = function (event) {
if ( event.state === null && window.location.hash === '' ) {
window.scrollTo( 0, 0 );
}
};
}
})(window, document);

I figured it out - I added
$("html").bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(){
clearInterval(runAnimation);
});
directly under
var runSmoothScroll = function (anchor, duration, easing, url) {
as runSmoothScroll is the function called to run the scrolling animation. So whenever that function is called, it adds the function for ending the animation, clearInterval(runAnimation) to the mousewheel. I also figured out a way to get the script to temporarily disable mousewheel.
/* =============================================================
Smooth Scroll 3.2
Animate scrolling to anchor links, by Chris Ferdinandi.
http://gomakethings.com
Easing support contributed by Willem Liu.
https://github.com/willemliu
Easing functions forked from Gaëtan Renaudeau.
https://gist.github.com/gre/1650294
URL history support contributed by Robert Pate.
https://github.com/robertpateii
Fixed header support contributed by Arndt von Lucadou.
https://github.com/a-v-l
Infinite loop bugs in iOS and Chrome (when zoomed) by Alex Guzman.
https://github.com/alexguzman
Free to use under the MIT License.
http://gomakethings.com/mit/
* ============================================================= */
window.smoothScroll = (function (window, document, undefined) {
'use strict';
// Feature Test
if ( 'querySelector' in document && 'addEventListener' in window && Array.prototype.forEach ) {
// SELECTORS
var scrollToggles = document.querySelectorAll('[data-scroll]');
// METHODS
// Run the smooth scroll animation
var runSmoothScroll = function (anchor, duration, easing, url) {
/*
//2/23/2014 Figured out how to disable mousewheel for a set amount of time
//disable mousewheel function
$("html").bind("scroll mousedown DOMMouseScroll mousewheel keyup", false);
//pause until animated scrolling is finished, then enable mousewheel
setTimeout(function(){
$("html").unbind("scroll mousedown DOMMouseScroll mousewheel keyup", false);
}, duration);
*/
//alternatively, can end the animation prematurely if mousewheel is used
$("html, body").bind("scroll mousedown DOMMouseScroll mousewheel keyup", function(){
clearInterval(runAnimation);
});
// SELECTORS
var startLocation = window.pageYOffset;
// Get the height of a fixed header if one exists
var scrollHeader = document.querySelector('[data-scroll-header]');
var headerHeight = scrollHeader === null ? 0 : scrollHeader.offsetHeight;
// Set the animation variables to 0/undefined.
var timeLapsed = 0;
var percentage, position;
// METHODS
// Calculate the easing pattern
var easingPattern = function (type, time) {
if ( type == 'easeInQuad' ) return time * time; // accelerating from zero velocity
if ( type == 'easeOutQuad' ) return time * (2 - time); // decelerating to zero velocity
if ( type == 'easeInOutQuad' ) return time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration
if ( type == 'easeInCubic' ) return time * time * time; // accelerating from zero velocity
if ( type == 'easeOutCubic' ) return (--time) * time * time + 1; // decelerating to zero velocity
if ( type == 'easeInOutCubic' ) return time < 0.5 ? 4 * time * time * time : (time - 1) * (2 * time - 2) * (2 * time - 2) + 1; // acceleration until halfway, then deceleration
if ( type == 'easeInQuart' ) return time * time * time * time; // accelerating from zero velocity
if ( type == 'easeOutQuart' ) return 1 - (--time) * time * time * time; // decelerating to zero velocity
if ( type == 'easeInOutQuart' ) return time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration
if ( type == 'easeInQuint' ) return time * time * time * time * time; // accelerating from zero velocity
if ( type == 'easeOutQuint' ) return 1 + (--time) * time * time * time * time; // decelerating to zero velocity
if ( type == 'easeInOutQuint' ) return time < 0.5 ? 16 * time * time * time * time * time : 1 + 16 * (--time) * time * time * time * time; // acceleration until halfway, then deceleration
return time; // no easing, no acceleration
};
// Update the URL
var updateURL = function (url, anchor) {
if ( url === 'true' && history.pushState ) {
history.pushState( {pos:anchor.id}, '', '#' + anchor.id );
}
};
// Calculate how far to scroll
var getEndLocation = function (anchor) {
var location = 0;
if (anchor.offsetParent) {
do {
location += anchor.offsetTop;
anchor = anchor.offsetParent;
} while (anchor);
}
location = location - headerHeight;
if ( location >= 0 ) {
return location;
} else {
return 0;
}
};
var endLocation = getEndLocation(anchor);
var distance = endLocation - startLocation;
// Stop the scrolling animation when the anchor is reached (or at the top/bottom of the page)
var stopAnimation = function () {
var currentLocation = window.pageYOffset;
if ( position == endLocation || currentLocation == endLocation || ( (window.innerHeight + currentLocation) >= document.body.scrollHeight ) ) {
clearInterval(runAnimation);
}
};
// Scroll the page by an increment, and check if it's time to stop
var animateScroll = function () {
timeLapsed += 16;
percentage = ( timeLapsed / duration );
percentage = ( percentage > 1 ) ? 1 : percentage;
position = startLocation + ( distance * easingPattern(easing, percentage) );
window.scrollTo( 0, position );
stopAnimation();
};
// EVENTS, LISTENERS, AND INITS
updateURL(url, anchor);
var runAnimation = setInterval(animateScroll, 16);
};
// Check that anchor exists and run scroll animation
var handleToggleClick = function (event) {
// SELECTORS
// Get anchor link and calculate distance from the top
var dataID = this.getAttribute('href');
var dataTarget = document.querySelector(dataID);
var dataSpeed = this.getAttribute('data-speed');
var dataEasing = this.getAttribute('data-easing');
var dataURL = this.getAttribute('data-url');
// EVENTS, LISTENERS, AND INITS
event.preventDefault();
if (dataTarget) {
runSmoothScroll( dataTarget, dataSpeed || 500, dataEasing || 'easeInOutCubic', dataURL || 'false' );
}
};
// EVENTS, LISTENERS, AND INITS
// When a toggle is clicked, run the click handler
Array.prototype.forEach.call(scrollToggles, function (toggle, index) {
toggle.addEventListener('click', handleToggleClick, false);
});
// Return to the top of the page when back button is clicked and no hash is set
window.onpopstate = function (event) {
if ( event.state === null && window.location.hash === '' ) {
window.scrollTo( 0, 0 );
}
};
}
})(window, document);

Related

Three.js - Raycaster doesn't work properly on Ipad

i had some issues with Raycaster when i tested my code on mobile device. I realised the same problem appears on the official examples on threejs.org when you activate tactile touch( ex: https://threejs.org/examples/?q=inter#webgl_interactive_cubes ).
Is there an alternative to Raycaster to interact with objects in threejs ?
I am using Firefox 58.0.2 (64 bits) to test my three.js project and to simulate tactile touch.
Thanks in advance
Thanks for the response,
In my example, i had to drag a panorama and interact with objects inside the panorama.
Here is the event listeners that works perfectly for me, if it can help others
function onDocumentTouchStart( event ) {
console.log("TouchStart")
event.preventDefault();
event.clientX = event.touches[0].pageX;
event.clientY = event.touches[0].pageY;
onDocumentMouseDown( event );
}
function onDocumentTouchMove( event ) {
console.log("TouchMove")
if ( event.touches.length == 1 ) {
event.preventDefault();
lon = ( onPointerDownPointerX - event.touches[0].pageX ) * 0.1 + onPointerDownLon;
lat = ( event.touches[0].pageY - onPointerDownPointerY ) * 0.1 + onPointerDownLat;
}
}
function onDocumentMouseMove( event ) {
if ( isUserInteracting === true ) {
lon = ( onPointerDownPointerX - event.clientX ) * 0.1 + onPointerDownLon;
lat = ( event.clientY - onPointerDownPointerY ) * 0.1 + onPointerDownLat;
}
}
function onDocumentMouseDown( event ) {
event.preventDefault();
mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
raycaster.setFromCamera( mouse, camera );
var intersects = raycaster.intersectObjects( scene.children );
if ( intersects.length > 0 && intersects[0].object.name.includes("sphere")) {
INTERSECTED = intersects[0].object;
//some code
isUserInteracting = true
onPointerDownPointerX = event.clientX;
onPointerDownPointerY = event.clientY;
onPointerDownLon = lon;
onPointerDownLat = lat;
}
Is there an alternative to Raycaster to interact with objects in threejs ?
Raycaster does not add event listeners, that's application level code.
Many three.js examples only support mouse interaction. If you want to support touch devices, implement event listeners like touchstart and use the event information in order to perform a raycast.

jQuery UI Sortable: tolerance "intersect" doesn't work as expected (bug #8342)

9 days ago (at time of this writing) the following bug has been reopened:
Sortable: Incorrect behaviour (or incorrect documentation) of sortable option tolerance: 'intersect'
Unfortunately I can't wait for jQuery to fix this issue.
I have a single container with items that can be sorted vertically (all <div>s). These items have different heights (and none of those heights are predefined).
Is there a decent workaround available?
I wrote a workaround myself, inspired by dioslaska's solution to his own question here:
jQuery UI sortable tolerance option not working as expected
It works quite smoothly :)
Remove the tolerance option and use the following function as sort option:
function( e, ui ) {
var container = $( this ),
placeholder = container.children( '.ui-sortable-placeholder:first' );
var helpHeight = ui.helper.outerHeight(),
helpTop = ui.position.top,
helpBottom = helpTop + helpHeight;
container.children().each( function () {
var item = $( this );
if( !item.hasClass( 'ui-sortable-helper' ) && !item.hasClass( 'ui-sortable-placeholder' )) {
var itemHeight = item.outerHeight(),
itemTop = item.position().top,
itemBottom = itemTop + itemHeight;
if(( helpTop > itemTop ) && ( helpTop < itemBottom )) {
var tolerance = Math.min( helpHeight, itemHeight ) / 2,
distance = helpTop - itemTop;
if( distance < tolerance ) {
placeholder.insertBefore( item );
container.sortable( 'refreshPositions' );
return false;
}
} else if(( helpBottom < itemBottom ) && ( helpBottom > itemTop )) {
var tolerance = Math.min( helpHeight, itemHeight ) / 2,
distance = itemBottom - helpBottom;
if( distance < tolerance ) {
placeholder.insertAfter( item );
container.sortable( 'refreshPositions' );
return false;
}
}
}
});
}

jQuery tools scrollable touch trigger

I am working with a touch based slideshow for the iPad using Jquery tools scrollable
http://jquerytools.org/demos/scrollable/vertical.html
It works great and does everything I want, but if my finger is ANYWHERE on the slider and moves every so slightly it triggers the slider to change sliders, is there a way I can change how much you need to drag your finger to change slide, or set specific areas where you can swipe to change slide?
You disable touch events on the "constructor" for the object, like this:
root = $('#content').scrollable({
keyboard:false,
mousewheel: false,
touch: false
});
I needed to do something similar where Scrollable was way too sensitive on an iPad. Here's what I changed to make it less sensitive for horizontal swiping:
// touch event
if (conf.touch) {
var touch = {};
itemWrap[0].ontouchstart = function(e) {
var t = e.touches[0];
touch.x = t.clientX;
touch.y = t.clientY;
};
itemWrap[0].ontouchmove = function(e) {
// only deal with one finger
if (e.touches.length == 1 && !itemWrap.is(":animated")) {
var t = e.touches[0],
deltaX = touch.x - t.clientX,
deltaY = touch.y - t.clientY;
self[vertical && deltaY > 0 || !vertical && deltaX > 0 ? 'next' : 'prev']();
e.preventDefault();
}
};
}
Becomes
// touch event
if (conf.touch) {
var touch = {};
itemWrap[0].ontouchstart = function(e) {
var t = e.touches[0];
touch.x = t.clientX;
touch.y = t.clientY;
};
itemWrap[0].ontouchmove = function(e) {
// only deal with one finger
if (e.touches.length == 1 && !itemWrap.is(":animated")) {
var t = e.touches[0],
deltaX = touch.x - t.clientX,
deltaY = touch.y - t.clientY;
if(deltaX > 200 || deltaX < -200) { // new line
self[vertical && deltaY > 0 || !vertical && deltaX > 0 ? 'next' : 'prev']();
} // new line
e.preventDefault();
}
};
}
Adjust the 200 to be however far you want folks to have to drag their finger before it changes to the next slide. Likewise, if you want to control a vertical scroller change deltaX in the new code to deltaY:
if(deltaY > 200 || deltaY < -200) { // new line
self[vertical && deltaY > 0 || !vertical && deltaX > 0 ? 'next' : 'prev']();
} // new line
If you're working with the minimized version of jQuery Tools you can use this code:
// horizontal change
if(h > 200 || h < -200) {
b[j && d > 0 || !j && h > 0 ? "next" : "prev"]();
}
// vertical change
if(d > 200 || d < -200) {
b[j && d > 0 || !j && h > 0 ? "next" : "prev"]();
}

iPad swipe Gesture Mobile Safari

I have been googling around for a bit and am trying to determine how to do a simple swipe event across an html element such as a div, to cause some action to happen in javascript.
<div id="swipe_me">
Swipe Test
</div>
Can someone show me or point me to some documentation?
javascript.
something a bit like (untested code)
onInitialized: function(e, slider) {
var time = 1000, // allow movement if < 1000 ms (1 sec)
range = 100, // swipe movement of 50 pixels triggers the slider
x = 0, t = 0, touch = "ontouchend" in document,
st = (touch) ? 'touchstart' : 'mousedown',
mv = (touch) ? 'touchmove' : 'mousemove',
en = (touch) ? 'touchend' : 'mouseup';
slider.$window
.bind(st, function(e){
// prevent image drag (Firefox)
e.preventDefault();
t = (new Date()).getTime();
x = e.originalEvent.touches ? e.originalEvent.touches[0].pageX : e.pageX;
})
.bind(en, function(e){
t = 0; x = 0;
})
.bind(mv, function(e){
e.preventDefault();
var newx = e.originalEvent.touches ? e.originalEvent.touches[0].pageX : e.pageX,
r = (x === 0) ? 0 : Math.abs(newx - x),
// allow if movement < 1 sec
ct = (new Date()).getTime();
if (t !== 0 && ct - t < time && r > range) {
if (newx < x) { slider.goForward(); }
if (newx > x) { slider.goBack(); }
t = 0; x = 0;
}
});
}

Set min/max for each range handle in jQuery UI slider?

I'm using a jQuery slider where users can select a time range between 00:00 and 1d+12:00. 36 hours all together.
Anyway.
I would like to apply min and max values to my handles based on what they're set to. These are my requirements:
left handle can never go over midnight on the next day (max is 24 hours)
left handle can never go more left than -24 hours from right handle (min is right handle value minus 24 hours)
right handle can never go more than +24 hours from the left handle (max is left handle value plus 24 hours)
As I understand, minimum and maximum values can only be applied to single handle slider control and not to range slider?
Is it possible to set minimums and maximums individually to both handles?
I've tried initializing it this way but no luck:
$(".timing-slider", timing).slider({
range: true,
min: [0, 0],
max: [24, 36],
}
This jQuery UI slider extension satisfies all upper requirements
I've managed to change default jQuery UI slider to include a few more configuration properties:
minRangeSize - sets minimum range size so ranges can't be narrower than this setting
maxRangeSize - sets maximum range size so ranges can't be wider than this setting
autoShift - when set to true it automatically drags the other handle along when range width reaches maximum; when set to false handle just can't be moved beyond maximum range width
lowMax - sets the lower handle upper boundary so it's impossible to set lower handle beyond this value
topMin - sets the upper handle lower boundary so it's impossible to set upper handle below this value
This is a working example of such range slider.
This is the extra code that has to be run after jQuery slider. It actually rewrites one of its internal functions to also check the new settings. This code will only change slider code when slider script has been loaded (hence the first if statement that checks whether slider widget has been loaded):
(function ($) {
if ($.ui.slider)
{
// add minimum range length option
$.extend($.ui.slider.prototype.options, {
minRangeSize: 0,
maxRangeSize: 100,
autoShift: false,
lowMax: 100,
topMin: 0
});
$.extend($.ui.slider.prototype, {
_slide: function (event, index, newVal) {
var otherVal,
newValues,
allowed,
factor;
if (this.options.values && this.options.values.length)
{
otherVal = this.values(index ? 0 : 1);
factor = index === 0 ? 1 : -1;
if (this.options.values.length === 2 && this.options.range === true)
{
// lower bound max
if (index === 0 && newVal > this.options.lowMax)
{
newVal = this.options.lowMax;
}
// upper bound min
if (index === 1 && newVal < this.options.topMin)
{
newVal = this.options.topMin;
}
// minimum range requirements
if ((otherVal - newVal) * factor < this.options.minRangeSize)
{
newVal = otherVal - this.options.minRangeSize * factor;
}
// maximum range requirements
if ((otherVal - newVal) * factor > this.options.maxRangeSize)
{
if (this.options.autoShift === true)
{
otherVal = newVal + this.options.maxRangeSize * factor;
}
else
{
newVal = otherVal - this.options.maxRangeSize * factor;
}
}
}
if (newVal !== this.values(index))
{
newValues = this.values();
newValues[index] = newVal;
newValues[index ? 0 : 1] = otherVal;
// A slide can be canceled by returning false from the slide callback
allowed = this._trigger("slide", event, {
handle: this.handles[index],
value: newVal,
values: newValues
});
if (allowed !== false)
{
this.values(index, newVal, true);
this.values((index + 1) % 2, otherVal, true);
}
}
} else
{
if (newVal !== this.value())
{
// A slide can be canceled by returning false from the slide callback
allowed = this._trigger("slide", event, {
handle: this.handles[index],
value: newVal
});
if (allowed !== false)
{
this.value(newVal);
}
}
}
}
});
}
})(jQuery);

Resources