Calling functions when the mouse wheel moves - javascript

I am a beginner at using javascript and jquery and I don't know a whole lot yet. I am trying to make some code that would call different functions if the mouse wheel moves in certain directions that is compatible with most or all programs. Could some one show me using an example piece of code how to implement this?
This is how I would need it to be set up
// JavaScript Document
...
...
...
...
function wheelMove(){
// NOTE: I'd like the event of scrolling not to fire
// (i.e return false; or something like it)
// if variables need to be set, they can go here
//...
//...
//...
if (// some code to detect if the wheel is moving towards the right){
var sRight = // some code to detect the speed in this direction;
moveRight(sRight); // calls a function when it moves right;
}
if (// some code to detect if the wheel is moving towards the left){
var sLeft = // some code to detect the speed in this direction;
moveLeft(sLeft); // calls a function when it moves left;
}
if (// some code to detect if the wheel is moving towards the up){
var sUp = // some code to detect the speed in this direction;
moveUp(sUp); // calls a function when it moves up;
}
if (// some code to detect if the wheel is moving towards the down){
var sDown = // some code to detect the speed in this direction;
moveDown(sDown); // calls a function when it moves down;
}
}

Here is an example (and here it is on jsfiddle.com):
$( '#scrollCatcher' ).on( 'mousewheel', function ( event ) {
// crude check to see events are supported
if ( typeof event.originalEvent.wheelDeltaX === 'undefined'
|| typeof event.originalEvent.wheelDeltaY === 'undefined' ) {
console.log( "could not find mouse deltas" );
return;
}
var deltaX = event.originalEvent.wheelDeltaX;
var deltaY = event.originalEvent.wheelDeltaY;
var scrolledLeft = deltaX < 0;
var scrolledRight = deltaX > 0;
var scrolledUp = deltaY < 0;
var scrolledDown = deltaY > 0;
clearDisplay();
if ( scrolledLeft ) { display( 'scrolled left' ); }
if ( scrolledRight ) { display( 'scrolled right' ); }
if ( scrolledUp ) { display( 'scrolled up' ); }
if ( scrolledDown ) { display( 'scrolled down' ); }
});
function clearDisplay () {
$( '#scrollCatcher' ).text( '' );
}
function display( message ) {
$( '#scrollCatcher' ).text( $( '#scrollCatcher' ).text() + message + ' ' );
}
To explain deltaX and deltaY are the distance travelled by the scroll wheel since the last event. Where there is display you could replace it with you own code. For example:
if ( scrolledLeft ) { moveLeft( deltaX ) }

Related

Horizontal scrolling with mouse wheel in vanilla JS

I'm trying to migrate some jQuery code to vanilla JS that modifies the mouse wheel behavior to scroll a site horizontally instead of vertically:
jQuery:
var wheel = function() {
var width = $( window ).width();
if ( width > 954 ) {
$( 'html' ).on( 'wheel', function( e ) {
e.preventDefault();
if ( Math.abs( e.originalEvent.deltaY ) >= Math.abs( e.originalEvent.deltaX ) ) {
this.scrollLeft += ( e.originalEvent.deltaY * 10 );
} else {
this.scrollLeft -= ( e.originalEvent.deltaX * 10 );
}
} );
} else {
$( 'html' ).off( 'wheel' );
}
}
wheel();
$( window ).on( 'resize', wheel );
As you can see ( if (width > 954) ), the new behavior is just set on desktops, not mobile nor tablet devices.
This is the vanilla JS code I came up with:
Vanilla JS:
var wheel = function() {
var width = window.innerWidth;
var scroll = function( e ) {
e.preventDefault();
if ( Math.abs( e.deltaY ) >= Math.abs( e.deltaX ) ) {
this.scrollLeft += ( e.deltaY * 10 );
} else {
this.scrollLeft -= ( e.deltaX * 10 );
}
}
if ( width > 954 ) {
document.documentElement.addEventListener( 'wheel', scroll );
} else {
document.documentElement.removeEventListener( 'wheel', scroll );
}
}
wheel();
window.addEventListener( 'resize', wheel );
But, when I resize the window to the tablet/mobile width, the horizontal scrolling is not disabled and I cannot scroll the site vertically. It seems as if the removeEventListener() function is not really removing my listener function.
Any ideas about what's going on here?
You are binding wheel handler many times as you resize the window. I would suggest to bind it once and then check the window width in it. Maybe something like this:
var scroll = function( e ) {
var width = window.innerWidth;
if(width <= 954) return;
e.preventDefault();
if ( Math.abs( e.deltaY ) >= Math.abs( e.deltaX ) ) {
this.scrollLeft += ( e.deltaY * 10 );
} else {
this.scrollLeft -= ( e.deltaX * 10 );
}
}
document.documentElement.addEventListener( 'wheel', scroll);

How can I detect window scroll ended in javascript?

I want to add a class to selected element after scroll ended. How can I detect scroll ended in JS?
HTML
<ul class="list" id="wrapper">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li id="element">7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
JS
const element = document.getElementById('element');
const y = element.getBoundingClientRect().top + window.scrollY;
window.scroll({
top: y,
behavior: 'smooth'
});
JSBIN EXAMPLE
There is natively no event to tell when a smooth-scroll ends.
There is also no standard behavior for how this smooth-scroll should occur, no defined duration, no defined timing function (Chrome uses an ease-in-out function while Firefox uses a linear one), and added to that, a smooth-scroll can be canceled in the middle by an other call to the scroll algorithm, or even have no effect at all...
So this detection is not that easy.
The best way I found for now is to start a requestAnimationFrame powered loop which will check every painting frame (right after the scroll operations), if our target is at the same position. As soon as it has been at the same position for more than two frames, we assume the scrolling ended. That's when we can check if it succeeded, simply by checking if we are at the expected position:
const trigger = document.getElementById( 'trigger' );
const scroll_forcer = document.getElementById( 'scroll_forcer' );
let scrolling = false; // a simple flag letting us know if we're already scrolling
trigger.onclick = (evt) => startScroll();
function startScroll() {
setTimeout(()=> {
scroll_forcer.classList.add( "scrolling" )
smoothScrollTo( { top: 1000 } )
.catch( (err) => {
/*
here you can handle when the smooth-scroll
gets disabled by an other scrolling
*/
console.error( 'failed to scroll to target' );
} )
// all done, lower the flag
.then( () => scroll_forcer.classList.remove( "scrolling" ) );
}, 10);
};
/*
*
* Promised based window.scrollTo( { behavior: 'smooth' } )
* #param { Element } elem
** ::An Element on which we'll call scrollIntoView
* #param { object } [options]
** ::An optional scrollToOptions dictionary
* #return { Promise } (void)
** ::Resolves when the scrolling ends
*
*/
function smoothScrollTo( options ) {
return new Promise( (resolve, reject) => {
const elem = document.scrollingElement;
let same = 0; // a counter
// last known scroll positions
let lastPos_top = elem.scrollTop;
let lastPos_left = elem.scrollLeft;
// pass the user defined options along with our default
const scrollOptions = Object.assign( {
behavior: 'smooth',
top: lastPos_top,
left: lastPos_left
}, options );
// expected final position
const maxScroll_top = elem.scrollHeight - elem.clientHeight;
const maxScroll_left = elem.scrollWidth - elem.clientWidth;
const targetPos_top = Math.max( 0, Math.min( maxScroll_top, scrollOptions.top ) );
const targetPos_left = Math.max( 0, Math.min( maxScroll_left, scrollOptions.left ) );
// let's begin
window.scrollTo( scrollOptions );
requestAnimationFrame( check );
// this function will be called every painting frame
// for the duration of the smooth scroll operation
function check() {
// check our current position
const newPos_top = elem.scrollTop;
const newPos_left = elem.scrollLeft;
// we add a 1px margin to be safe
// (can happen with floating values + when reaching one end)
const at_destination = Math.abs( newPos_top - targetPos_top) <= 1 &&
Math.abs( newPos_left - targetPos_left ) <= 1;
// same as previous
if( newPos_top === lastPos_top &&
newPos_left === lastPos_left ) {
if( same ++ > 2 ) { // if it's more than two frames
if( at_destination ) {
return resolve();
}
return reject();
}
}
else {
same = 0; // reset our counter
// remember our current position
lastPos_top = newPos_top;
lastPos_left = newPos_left;
}
// check again next painting frame
requestAnimationFrame( check );
}
});
}
#scroll_forcer {
height: 5000vh;
background-image: linear-gradient(to bottom, red, green);
background-size: 100% 100px;
}
#scroll_forcer.scrolling {
filter: grayscale(70%);
}
.as-console-wrapper {
max-height: calc( 50vh - 30px ) !important;
}
<button id="trigger">click to scroll</button>
<div id="scroll_forcer">
</div>
You could use requestAnimationFrame to detect when the scrollTop is greater than y
requestAnimationFrame is way better than setting both an interval and an event listener on scroll, for a matter of performance.
const element = document.getElementById('element');
const y = element.getBoundingClientRect().top + window.scrollY;
function checkScrollEnd() {
if ((window.scrollY || document.body.scrollTop || document.documentElement.scrollTop) < y) {
window.requestAnimationFrame(checkScrollEnd);
}
else {
alert('end of scroll')
}
}
window.requestAnimationFrame(checkScrollEnd);
window.scroll({
top: y,
behavior: 'smooth'
});
Example fiddle
Hope this will help you
<script type="text/javascript">
jQuery(
function ($) {
$(window).on("scroll", function () {
var scrollHeight = $(document).height();
var scrollPosition = $(window).height() + $(window).scrollTop();
if (scrollHeight - scrollPosition <= 180) {
// when scroll to bottom of the page
// your function to call
}
});
}
);
</script>
Solution by LINK
const onScrollStop = (callback) => {
// Make sure a valid callback was provided
if (!callback || typeof callback !== 'function') return;
// Setup scrolling variable
let isScrolling;
// Listen for scroll events
window.addEventListener('scroll', (event) => {
// Clear our timeout throughout the scroll
window.clearTimeout(isScrolling);
// Set a timeout to run after scrolling ends
isScrolling = setTimeout(() => {
// Run the callback
callback();
}, 66);
}, false);
};
onScrollStop(() => {
console.log('Scrolling has stopped.');
});
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
//Your Stuff
}
});

How to make Syncing two Divs scroll positions smoother

I am trying to sync two scrollable DIVS scroll positions.
Methods followed :
Method - 1 : on-scroll event setting the scrollTop of other DIV.
problem : scroll event executed at the end and UI is sluggish in iOS safari.
Method - 2 : used setInterval to sync both scroll positions.
Problem : iOS does not execute timer functions during scroll,
so scroll positions synced at the end. Again this is more sluggish.
Tried, timers fix as mentioned in many blogs but still no grace.
Method -3 : Tried custom scrollbar, so iScroll and tried to sync both on scroll event,
Problem : this seems better but in iOS still it is sluggish!!!
Method -4 : Tried custom scrollbar, so iScroll and tried to sync both on scroll event,
Problem : Used iScroll but using timers rather depending on onScroll event,
But during touchmove, iOS is busy in providing animations
rather executing required timers till touchend.
Below code refers to this method. It is also sluggish.
var active = .., other = ...
// active : active Scrolling element
// other : Element to be in sync with active
window.setInterval(function () {
var y;
if (active) {
y = active.y;
} else {
return;
}
var percentage = -y / (active.scrollerHeight - active.wrapperHeight);
var oscrollTop = percentage * (other.scrollerHeight - other.wrapperHeight);
if (-other.maxScrollY >= toInt(oscrollTop)) {
other.scrollTo(0, -toInt(oscrollTop));
}
}, 20);
How can make syncing scroll positions of two scrollable DIVS smoother. Please suggest me something, it is irritating me.
relying on the scroll events (OPs method 1) is fine for a desktop implementation. the scroll event fires before the screen is updated. on mobile devices, especially iOS this is not the case. due to limited resources the scroll event only fires after the user completed (lifted his finger) the scroll operation.
implementing manual scrolling
to have a scroll event while the user scrolls on iOS requires to implement the scrolling manually.
register the touchstart event. and get the first touch:
var element1 = document.getElementById('content1');
var element2 = document.getElementById('content2');
var activeTouch = null;
var touchStartY = 0;
var element1StartScrollTop = 0;
var element2scrollSyncFactor = 0;
document.addEventListener('touchstart', function(event) {
event.preventDefault();
var touch = event.changedTouches[0];
if ( activeTouch == null ) {
// implement check if touch started on an element you want to be scrollable
// save a reference to the scrolling element for the other functions
activeTouch = touch;
touchStartY = touch.screenY;
// if scroll content does not change do this calculation only once to safe compute and dom access time while animating
calcSyncFactor();
}
});
function calcSyncFactor()
{
// calculate a factor for scroll areas with different height
element2scrollSyncFactor = (element2.scrollHeight - element2.clientHeight) / (element1.scrollHeight - element1.clientHeight);
}
update your scroll position on finger movement:
document.addEventListener('touchmove', function() {
for ( var i = 0; i < event.changedTouches.length; i++ ) {
var touch = event.changedTouches[i];
if ( touch === activeTouch ) {
var yOffset = touch.screenY - touchStartY;
element1.scrollTop = element1StartScrollTop + (0 - yOffset);
syncScroll();
break;
}
}
});
function syncScroll()
{
element2.scrollTop = Math.round(element1.scrollTop * element2scrollSyncFactor);
}
it is possible to add a check that starts the scrolling only after the user has moved his finger some pixels. this way if the user clicks an element the document will not scroll some pixels.
cleanup after the user lifts the finger:
document.addEventListener('touchend', touchEnd);
document.addEventListener('touchcancel', touchEnd);
function touchEnd(event)
{
for ( var i = 0; i < event.changedTouches.length; i++ ) {
var touch = event.changedTouches[i];
if ( touch === activeTouch ) {
// calculate inertia and apply animation
activeTouch = null;
break;
}
}
}
to have the scrolling feel more natuaral apply the iOS rubber band effect and inertia. calculate the velocity of the scroll by comparing the last touchMove yOffset with the one before. from this velocity apply an animation (for example css transition) that slowly stops the scrolling
see FIDDLE. see result on iOS. the fiddle only implements the solution for touch devices. for desktop devices use OP's method 1. implement a condition which checks which method to use depending on device.
how to apply inertia with css transitions
it would be possible to animate in javascript with requestAnimationFrame. a probably more performant way on mobile might be the use of css transformations or css animations. although an elements scroll position can not be animated with css.
change the structure of the html to.
div: container with overflow: hidden
div: content with position: absolute
depending on content size use css property -webkit-transform: translateZ(0) on content div. this will create a new layer with its own backing surface, which will be composited on the gpu.
implement the functions described above so that they animate the content's top position instend of scrollTop
var element1 = document.getElementById('content1');
var element2 = document.getElementById('content2');
var activeTouch = null;
var touchStartY = 0;
var element1StartScrollTop = 0;
var element2scrollSyncFactor = 0;
var offsetY = 0;
var lastOffsetY = 0;
document.addEventListener('touchstart', function(event) {
event.preventDefault();
var touch = event.changedTouches[0];
if ( activeTouch == null ) {
activeTouch = touch;
touchStartY = touch.screenY;
// use offsetTop instead of scrollTop
element1StartScrollTop = element1.offsetTop;
// if scroll content does not change do this calculation only once to safe compute time while animating
calcSyncFactor();
// cancel inertia animations
element1.style.webkitTransition = 'none';
element2.style.webkitTransition = 'none';
}
});
function calcSyncFactor()
{
// calculate a factor for scroll areas with different height
// use the div's sizes instead of scrollTop
element2scrollSyncFactor = (element2.clientHeight - element2.parentNode.clientHeight) / (element1.clientHeight - element1.parentNode.clientHeight);
}
document.addEventListener('touchmove', function() {
for ( var i = 0; i < event.changedTouches.length; i++ ) {
var touch = event.changedTouches[i];
if ( touch === activeTouch ) {
lastOffsetY = offsetY;
offsetY = touch.screenY - touchStartY;
// use offsetTop instead of scrollTop
element1.style.top = (element1StartScrollTop + offsetY) + 'px';
syncScroll();
break;
}
}
});
function syncScroll()
{
element2.style.top = Math.round(element1.offsetTop * element2scrollSyncFactor) + 'px';
}
document.addEventListener('touchend', touchEnd);
document.addEventListener('touchcancel', touchEnd);
function touchEnd(event)
{
for ( var i = 0; i < event.changedTouches.length; i++ ) {
var touch = event.changedTouches[i];
if ( touch === activeTouch ) {
applyInertia();
activeTouch = null;
break;
}
}
}
when the user finishes scrolling and lifts his finger apply the inertia
function applyInertia()
{
var velocity = offsetY - lastOffsetY;
var time = Math.abs(velocity) / 150;
var element1EndPosition = element1.offsetTop + velocity;
element1.style.webkitTransition = 'top ' + time + 's ease-out';
element1.style.top = element1EndPosition + 'px';
element2.style.webkitTransition = 'top ' + time + 's ease-out';
element2.style.top = Math.round(element1EndPosition * element2scrollSyncFactor) + 'px';
}
the inertia is calculated from the velocity when the user lifted the finger. fiddle around with the values to get desired results. a rubberband effect could be implemented in this function aswell. to have no javascript involved applying css animations might be the trick. another way would be to register events for when the transitions finish. if the transition finishes and the scroll position is outside the container apply a new transition that animates the content back.
see FIDDLE. see result on iOS.

jittery mousewheel horizontal scrolling

I'm currently working on a smooth horizontal mousewheel scroll and firefox is giving me quite a a bit of a headache.
basically, whenever one fires the mouse wheel event that would execute the scroll, firefox replies with very disparate values, as in a scroll which should fire negative events fires the odd positive value (i.e. 30, 40, 43, -20, 30, -4), especially on smaller movements. that results more or less in the opposite of the desired result, as you can imagine.
is there any way to avoid that? I've tried throttling it a little bit, but the loss of fluidity in the movement makes it a no go.
for reference, the code for the scroll:
var scroll = function(e, d){
console.log(d);
$('html, body').animate(
{scrollLeft: '-=' + d},
10
);
e.preventDefault();
e.returnValue = false;
}
$('html, body').bind('mousewheel', scroll);
I found that the best, most consistent way of calculating mousewheel distance is to use three events: mousewheel, MozMousePixelScroll and DOMMouseScroll.
The last two events are mozilla-specific and they are available in different FF versions. They are more precise than the mousewheel event, but you need to adjust the delta to normalize the speed. Here is some code I used in the past:
DEMO: http://jsfiddle.net/6b28X/
var distance = 0;
var scroll = function(e){
e.preventDefault();
var original = e.originalEvent,
delta = 0,
hasPixelEvent = false;
// FF 3.6+
if ( 'HORIZONTAL_AXIS' in original && original.axis == original.HORIZONTAL_AXIS ) {
return; // prevents horizontal scroll in FF
}
if ( e.type == 'MozMousePixelScroll' ) {
hasPixelEvent = true;
delta = original.detail / -7;
// other gecko
} else if ( e.type == 'DOMMouseScroll' ) {
if ( hasPixelEvent ) {
return;
} else {
delta = original.detail * -3;
}
// webkit + IE
} else {
delta = original.wheelDelta / 7;
}
distance = Math.max(distance-delta, 0);
window.scrollTo( distance, 0 );
}
$(window).bind('mousewheel MozMousePixelScroll DOMMouseScroll', scroll);

Add swipe left/right to web page, but use default swipe up/down

I'm using padilicious to detect swiping gestures for web pages that will be viewed on iOS and desktops. It works great to swipe left/right for previous and next pages of my site. However, it seems to override the default behavior in iPhone/iPad when swiping up/down. I'd like an up/down swipe to scroll the page, which it does when I don't have padilicious running. Just having the code ignore up/down swipes doesn't seem to work.
The section of padilicious code that I've been
function processingRoutine() {
var swipedElement = document.getElementById(triggerElementID);
if ( swipeDirection == 'left' ) {
document.location = document.getElementById('nextPage').href;
} else if ( swipeDirection == 'right' ) {
document.location = document.getElementById('prevPage').href;
} else if ( swipeDirection == 'up' ) {
return;
} else if ( swipeDirection == 'down' ) {
return;
}
}
Remove event.preventDefault(); from all functions. In the function processingRoutine() {} add event.preventDefault(); for what you want.
function processingRoutine() {
var swipedElement = document.getElementById(triggerElementID);
if ( swipeDirection == 'left' ) {
// REPLACE WITH YOUR ROUTINES
//swipedElement.style.backgroundColor = 'orange';
event.preventDefault();
} else if ( swipeDirection == 'right' ) {
// REPLACE WITH YOUR ROUTINES
//swipedElement.style.backgroundColor = 'green';
event.preventDefault();
} else if ( swipeDirection == 'up' ) {
// REPLACE WITH YOUR ROUTINES
//swipedElement.style.backgroundColor = 'maroon';
} else if ( swipeDirection == 'down' ) {
// REPLACE WITH YOUR ROUTINES
//swipedElement.style.backgroundColor = 'purple';
}
}
there's a jquery library, which does the job (by not providing up/down methods): http://plugins.jquery.com/project/Touchwipe-iPhone-iPad-wipe-gesture
I'm not familiar with padilicious, but check and see if the ontouchmove="BlockMove(event);" is set anywhere, that prevents the page from scrolling like you describe, I'm not sure how you would get it to keep the vertical scrolling but swipe horizontally.
Edit: I've since found a really helpful overview for doing "native" feel iOS web apps, it might not be exactly what you're looking for, but could provide you with another avenue of approach to your problem. Check it out: http://matt.might.net/articles/how-to-native-iphone-ipad-apps-in-javascript/
Padilicious seems to be preventing default in all cases. See the call to event.preventDefault() in all cases.
function touchStart(event,passedName) {
// disable the standard ability to select the touched object
event.preventDefault();
You will have to change start, stop, ... handlers to not call preventDefault() in up and down cases.
I changed the script, this work:
// TOUCH-EVENTS SINGLE-FINGER SWIPE-SENSING JAVASCRIPT
// Courtesy of PADILICIOUS.COM and MACOSXAUTOMATION.COM
// this script can be used with one or more page elements to perform actions based on them being swiped with a single finger
var triggerElementID = null; // this variable is used to identity the triggering element
var fingerCount = 0;
var startX = 0;
var startY = 0;
var curX = 0;
var curY = 0;
var deltaX = 0;
var deltaY = 0;
var horzDiff = 0;
var vertDiff = 0;
var minLength = 72; // the shortest distance the user may swipe
var swipeLength = 0;
var swipeAngle = null;
var swipeDirection = null;
// The 4 Touch Event Handlers
// NOTE: the touchStart handler should also receive the ID of the triggering element
// make sure its ID is passed in the event call placed in the element declaration, like:
// <div id="picture-frame" ontouchstart="touchStart(event,'picture-frame');" ontouchend="touchEnd(event);" ontouchmove="touchMove(event);" ontouchcancel="touchCancel(event);">
function touchStart(event,passedName) {
// disable the standard ability to select the touched object
//event.preventDefault();
// get the total number of fingers touching the screen
fingerCount = event.touches.length;
// since we're looking for a swipe (single finger) and not a gesture (multiple fingers),
// check that only one finger was used
if ( fingerCount == 1 ) {
// get the coordinates of the touch
startX = event.touches[0].pageX;
startY = event.touches[0].pageY;
// store the triggering element ID
triggerElementID = passedName;
} else {
// more than one finger touched so cancel
touchCancel(event);
}
}
function touchMove(event) {
//event.preventDefault();
if ( event.touches.length == 1 ) {
curX = event.touches[0].pageX;
curY = event.touches[0].pageY;
} else {
touchCancel(event);
}
}
function touchEnd(event) {
//event.preventDefault();
// check to see if more than one finger was used and that there is an ending coordinate
if ( fingerCount == 1 && curX != 0 ) {
// use the Distance Formula to determine the length of the swipe
swipeLength = Math.round(Math.sqrt(Math.pow(curX - startX,2) + Math.pow(curY - startY,2)));
// if the user swiped more than the minimum length, perform the appropriate action
if ( swipeLength >= minLength ) {
caluculateAngle();
determineSwipeDirection();
processingRoutine();
touchCancel(event); // reset the variables
} else {
touchCancel(event);
}
} else {
touchCancel(event);
}
}
function touchCancel(event) {
// reset the variables back to default values
fingerCount = 0;
startX = 0;
startY = 0;
curX = 0;
curY = 0;
deltaX = 0;
deltaY = 0;
horzDiff = 0;
vertDiff = 0;
swipeLength = 0;
swipeAngle = null;
swipeDirection = null;
triggerElementID = null;
}
function caluculateAngle() {
var X = startX-curX;
var Y = curY-startY;
var Z = Math.round(Math.sqrt(Math.pow(X,2)+Math.pow(Y,2))); //the distance - rounded - in pixels
var r = Math.atan2(Y,X); //angle in radians (Cartesian system)
swipeAngle = Math.round(r*180/Math.PI); //angle in degrees
if ( swipeAngle < 0 ) { swipeAngle = 360 - Math.abs(swipeAngle); }
}
function determineSwipeDirection() {
if ( (swipeAngle <= 45) && (swipeAngle >= 0) ) {
swipeDirection = 'left';
} else if ( (swipeAngle <= 360) && (swipeAngle >= 315) ) {
swipeDirection = 'left';
} else if ( (swipeAngle >= 135) && (swipeAngle <= 225) ) {
swipeDirection = 'right';
}
/* else if ( (swipeAngle > 45) && (swipeAngle < 135) ) {
swipeDirection = 'down';
} else {
swipeDirection = 'up';
}*/
}
function processingRoutine() {
var swipedElement = document.getElementById(triggerElementID);
if ( swipeDirection == 'left' ) {
// REPLACE WITH YOUR ROUTINES
event.preventDefault();
swipedElement.style.backgroundColor = 'orange';
} else if ( swipeDirection == 'right' ) {
// REPLACE WITH YOUR ROUTINES
event.preventDefault();
swipedElement.style.backgroundColor = 'green';
}
/*else if ( swipeDirection == 'up' ) {
// REPLACE WITH YOUR ROUTINES
swipedElement.style.backgroundColor = 'maroon';
} else if ( swipeDirection == 'down' ) {
// REPLACE WITH YOUR ROUTINES
swipedElement.style.backgroundColor = 'purple';
}*/
}

Categories