View
 

Handling Shake Events

Page history last edited by Joël Galeran 1 week, 5 days ago Saved with comment

handle shaking the phone from side-to-side:

 

 

I've found a threshold of around 1.5 to be sufficient.

 

function watchForShake(threshold)
{
    var axl = new Accelerometer(); 
    axl.watchAcceleration
    (
        function (Accel)
        {
            if (true === Accel.is_updating)
            {
                return;
            }

            if (Accel.x >= threshold || Accel.x <= (0 - threshold))
            {
                // The user has shaken their device. Do something
                // ...
            }
        }
      , function(){}
      , {frequency : 750}
    );
}

---------------------------------------------------------------------------------------------------------------------
update suggestion 2011-02-20
By: Joey van der Bie 
Although the above script worked before, anno 2011 the behavior of the Accelerometer has slightly changed, 
Resulting in the need for a history variable.
A simple solution would be the following code, only if you want to use more axes I would advice using an Array as history.
update suggestion 2012-01-23

By: Joël Galeran

I added this :

document.addEventListener("deviceready", onDeviceReady, false); 

function onDeviceReady() {

     watchForShake(0.5);

}

 

<!DOCTYPE html>

<html>

  <head>

    <meta name="viewport" content="width=320; user-scalable=no" />

    <meta http-equiv="Content-type" content="text/html; charset=utf-8">

    <title>Accelerometer Shake Demo</title>

 

<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>

 

<script type="text/javascript" charset="utf-8">

var prevX = 1.0;

 

document.addEventListener("deviceready", onDeviceReady, false); 

function onDeviceReady() {

     watchForShake(0.5);

}

 

function watchForShake(threshold)

{

   var axl = new Accelerometer(); 

   axl.watchAcceleration(

       function (Accel)

       {

           if (true === Accel.is_updating){

               return;

           }

           var diffX = Math.abs(Accel.x) - prevX;

 

           if (diffX >= threshold)

           {

               // The user has shaken their device. Do something

               alert("You have made a milkshake!");

           }

          prevX = Math.abs(Accel.x);

       }

     , function(){}

     , {frequency : 100}

   );

}

 </script>

 

  </head>

  <body id="stage" class="theme">

          Shake it baby!

  </body>

</html>