Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Detecting device movement

From: Mobile Web Design & Development Fundamentals

Video: Detecting device movement

Beyond capturing just simple changes in device orientation, you can also detect and respond to more complex device motion events. You can do this by listening to the DeviceMotion event, and there's also an onDeviceMotion event off of the Window object. So when you register an event handler for DeviceMotion, the event handler function will be called with an event that describes a DeviceMotion event. The DeviceMotion event contains several properties. There is the property for acceleration, which itself contains properties X, Y, and Z that describe acceleration in meters per second squared on three different axes: forward and back, up or down, and left to right.

Detecting device movement

Beyond capturing just simple changes in device orientation, you can also detect and respond to more complex device motion events. You can do this by listening to the DeviceMotion event, and there's also an onDeviceMotion event off of the Window object. So when you register an event handler for DeviceMotion, the event handler function will be called with an event that describes a DeviceMotion event. The DeviceMotion event contains several properties. There is the property for acceleration, which itself contains properties X, Y, and Z that describe acceleration in meters per second squared on three different axes: forward and back, up or down, and left to right.

There is also the accelerationIncludingGravity property, which is the same as the regular acceleration property, but it includes the effects of gravity. The rotationRate contains properties alpha, beta, and gamma that measure the rotation speed for three rotation axes. And then there's the interval, which is the number of milliseconds since the last time a DeviceMotion event came through. Let's see a code example for how this works. And so here I am in my devicemotion_start file, and I've opened this up from the Exercise Files folder. And I've also got my ExampleSnippets file, and let's scroll down to the Complex Motion area.

So what we're going to do in the devicemotion file is put in some code that responds to DeviceMotion events and displays the motion of the iPhone in the X, Y, and Z axes, and also displays the rotation events in the pitch, yaw, and roll. So let's go back to the snippets code and copy that in. So this is the code I'm going to copy over. So select all of this, and I'll explain what it does. So we'll copy that and we'll paste it in.

So now that I've pasted the code, let's go back and take a look what it does. So right down here at the bottom, I have window.addEventListener, and I'm listening for the devicemotion event. And when the devicemotion event occurs, it will call the handleMotion event handler, which I've defined up here. And this is the handleMotion event handler and it takes the event argument. So let's take a walk through the code. I've got a few local variables here that will hold the values for the acceleration values and the rotation values.

And rather than be inundated with device motion events every few milliseconds, I've got a little time to measure here that starts out at the value of zero. And what I'm doing is I'm checking to see if the interval between this device motion and the last one, if the time elapsed is greater than 1.5 seconds, so this will limit the amount the display updates and shows new numbers. So I'm just adding the current interval to the time and if the time is less than a second and a half, I just return; otherwise, we let it pass and we reset the time counter to zero for the next time around, and then we display the information to the user.

So we've got the displayStr here, and it's going to be the Acceleration label. Then what I'm doing is I'm using the Math library here to round up the values of the X, Y, and Z acceleration values, because the accelerometer and the gyroscope in the iPhone are really hypersensitive, and if we didn't do this we would be getting a whole bunch of very long floating-point numbers being displayed on the screen. So just to limit this to integer numbers and numbers that we can easily see changing every one and the half seconds, I'm just rounding the values up here. So then I have the display string, and I'm adding the values for X, Y, and Z in here, and I'm doing the same thing for the Rotation Rate.

Only in this case, rather than X, Y, and Z, I've got the alpha, beta, and gamma values that I'm saving off, and I'm just rounding them, again, to the nearest integer value, just to make the data little more easy to consume. So then I add that to the display string and then down here in the document's output div right here, I simply set the innerHTML of that div to be the displayStr which contains all the values that we just measured. All right, so I'm going to save this, and I'm going to deploy it up to my server. Now I have to demonstrate this on a physical iPhone and the reason for that is because the iPhone Simulator does not provide a simulation value for the accelerometer or the gyroscope, so let's switch over to the physical iPhone, and we can see this work.

So here I'm on the physical iPhone, and you can see that I'm holding the phone, and we're seeing integer values and even though I'm not moving the phone very much at the moment, you can see that I'm getting a little bit of residual rotation rate. And I'm just going to move the phone around and you can see that as I move the phone around in different axes, you see how the numbers are changing and we're getting different values for the acceleration in the X and Y directions, and because the phone is also rotating while this is happening, we're seeing the rotation rate change as well.

So this is actually a pretty cool little feature. You can use this feature to create web applications that are aware of motion and rotation using the iPhone and the accelerometer and the gyroscope.

Show transcript

This video is part of

Image for Mobile Web Design & Development Fundamentals
Mobile Web Design & Development Fundamentals

46 video lessons · 24274 viewers

Joe Marini
Author

 
Expand all | Collapse all
  1. 2m 48s
    1. Welcome
      1m 2s
    2. Using the exercise files
      1m 46s
  2. 29m 25s
    1. Understanding the mobile context
      8m 5s
    2. A survey of mobile sites
      11m 44s
    3. Targeting mobile browsers
      4m 31s
    4. Previewing a complete mobile site
      5m 5s
  3. 27m 20s
    1. Designing for one web
      3m 43s
    2. Using well-defined web standards
      3m 45s
    3. Designing mobile-friendly pages
      3m 40s
    4. Being crisp, clean, and succinct
      5m 45s
    5. Minimizing input where possible
      6m 47s
    6. Focusing on the core scenarios
      3m 40s
  4. 1h 13m
    1. Installing the tools
      3m 52s
    2. Setting up a local web server
      9m 13s
    3. Installing device emulators
      17m 5s
    4. Using device emulators
      13m 9s
    5. Downloading Modernizr and Mobile Boilerplate
      6m 22s
    6. Building a first mobile web page
      5m 43s
    7. Developing mobile pages with desktop browsers
      8m 6s
    8. Exploring useful mobile web development resources
      10m 23s
  5. 53m 26s
    1. Reviewing mobile markup languages
      5m 10s
    2. Understanding content adaptation approaches
      10m 32s
    3. Controlling the viewport layout
      12m 50s
    4. Designing forms
      13m 30s
    5. Using CSS media queries
      11m 24s
  6. 1h 11m
    1. Detecting client capabilities with script
      10m 8s
    2. Caching information with local storage
      9m 16s
    3. Determining position with geolocation
      12m 52s
    4. Minimizing HTTP requests with data URLs
      7m 39s
    5. Understanding user agent detection
      9m 8s
    6. Using server-side detection with PHP
      6m 52s
    7. Using server-side detection with ASP.NET
      4m 54s
    8. Using HTML5 Boilerplate for mobile
      11m 6s
  7. 39m 22s
    1. Measuring performance
      7m 41s
    2. Creating full-screen web apps
      6m 30s
    3. Customizing the user interface
      5m 14s
    4. Detecting orientation changes
      3m 58s
    5. Detecting device movement
      5m 21s
    6. Using touch events
      10m 38s
  8. 47m 14s
    1. Taking a look at the finished site
      7m 40s
    2. Examining the header and background image style on the Home page
      10m 10s
    3. Examining the hover effect and layout styles on the Tours page
      6m 42s
    4. Examining mobile forms on the Contact page
      9m 45s
    5. Viewing and testing the mobile site on emulators
      8m 11s
    6. Viewing the site on devices
      4m 46s
  9. 2m 34s
    1. Goodbye
      2m 34s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ.

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed Mobile Web Design & Development Fundamentals.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferencesfrom the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.