jQM - Swipe distance / direction plugin

by LuckyCat

HTML

<!DOCTYPE html>
<html>
    <head>
        <title>jQM Complex Demo</title>
        <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=no; target-densityDpi=device-dpi"/>
        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css" />
        <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>    
    </head>
    <body>
        <div data-role="page" id="index">
            <div data-theme="b" data-role="header">
                <h1>Index page</h1>
            </div>
            
            <div data-role="content">

            </div>
        </div>    
    </body>
</html>

JavaScript

var gnStartX = 0;
var gnStartY = 0;
var gnCurrentX = 0;
var gnCurrent = 0;
var gnEndX = 0;
var gnEndY = 0;

var globalMovement = 0;


$(document).on('mousedown', function(event){
    gnStartX = event.pageX;
    gnStartY = event.pageY;
    event.preventDefault();
});

$(document).on('mousemove', function(event){
    var newPosX = event.pageX;
    var newPosY = event.pageY; 
    var distance = Math.ceil(nthroot(Math.pow((newPosX - gnStartX),2) + Math.pow((newPosY - gnStartY),2), 2));    
    event.preventDefault();
});

$(document).on('mouseup', function(event){
    gnEndX = event.pageX;
    gnEndY = event.pageY;  
    var distance = Math.ceil(nthroot(Math.pow((gnEndX - gnStartX),2) + Math.pow((gnEndY - gnStartY),2), 2));
    globalMovement+=distance;
    
    if(Math.abs(gnEndX - gnStartX) > Math.abs(gnEndY - gnStartY)) {
        if(gnEndX > gnStartX) {
            console.log("Swipe Right - Distance " + distance + 'px');
        } else {
            console.log("Swipe Left - Distance " + distance + 'px');     
        }
    } else {
        if(gnEndY > gnStartY) {
            console.log("Swipe Bottom - Distance " + distance + 'px');  
        } else {
            console.log("Swipe Top - Distance " + distance + 'px');      
        }        
    }  
    // alert('Global movement = '  + globalMovement);
    event.preventDefault();      
});

function nthroot(x, n) {
  try {
    var negate = n % 2 == 1 && x < 0;
    if(negate)
      x = -x;
    var possible = Math.pow(x, 1 / n);
    n = Math.pow(possible, n);
    if(Math.abs(x - n) < 1 && (x > 0 == n > 0))
      return negate ? -possible : possible;
  } catch(e){}
}