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

Using touch events

From: Mobile Web Design & Development Fundamentals

Video: Using touch events

One of the really cool things about modern smartphone browsers is that you can use touch events in them. Touch events are sort of like mouse events, but there can be more than one touch point on the screen, because you're using your fingers, not using a mouse. There are four events that are sent for touch-related events. The first one is touchstart, and that's sent when a finger first touches the surface; there's touchmove, which is sent as the finger moves across the surface; there's touchend, which is sent when the finger lifts from the surface; and there's the touchcancel event, which is sent if the system cancels the touch event that's in progress.

Using touch events

One of the really cool things about modern smartphone browsers is that you can use touch events in them. Touch events are sort of like mouse events, but there can be more than one touch point on the screen, because you're using your fingers, not using a mouse. There are four events that are sent for touch-related events. The first one is touchstart, and that's sent when a finger first touches the surface; there's touchmove, which is sent as the finger moves across the surface; there's touchend, which is sent when the finger lifts from the surface; and there's the touchcancel event, which is sent if the system cancels the touch event that's in progress.

A touch event contains a lot of information about what is happening on the screen. It contains four Boolean values, altKey, shiftKey, metaKey, and ctrlKey, which indicate whether the associated key was held down for that event. You might be saying to yourself, "Well, wait a second. How can that possibly happen on an iPhone?" Well, you have to remember that touch events happen on more than just phones; they also happen on laptops because of the touch-sensitive pads. They happen on touchscreens with PCs. So that's why those fields are provided. Now, they don't happen on the iPhone obviously, but they do happen on other touch-sensitive devices.

But we won't be using it, because we won't be able to detect that kind of property on the phone. In addition to those four properties, there's the touches array which is a list of all the touches that are currently being tracked on the screen. There is also the changedTouches array, which is the array of all the touches that have changed in this event. Remember, you can have multiple touches because you can have multiple fingers on the screen at any one time. There's also the targetTouches, which is the array of all the touches for a given target on the screen. And then there's rotation and scale, and that measures the rotation and distance between the fingers since the initial event.

So for example, in the case of scale, that starts out as 1.0 when you have two fingers and if the fingers move farther apart, that value will be bigger than 1.0; and if the value is less than 1.0, it means the fingers have moved closer together. So you can use that information to simulate pinching and zooming events. Now, in those arrays, each one of those touch objects contains six properties that measure the point on the screen where the finger currently is. There is clientX and clientY, so those are the Windows viewport coordinates; there's pageX and pageY, and those are in document coordinates; and there's screenX, and screenY, and those are in screen coordinates.

There's also an identifier which uniquely identifies this particular touch and the target property which is the target that the touch is associated with. It's probably easiest to see this in action in order to understand what's going on, so let's take a look at a brief simulation. Suppose we have a screen that looks like this. When the user puts their finger on the screen, that generates a touchstart event, and at this point, the touches array has a length of 1 because there's one finger and touches of 0 contains the coordinate information about the touch, along with the event target.

As the finger moves across the screen, it generates touch events along the way. In this case, the changedTouches.length would be 1, and each of the changedTouches will contain coordinate information about the touch as it updates when the finger moves across the screen. Finally, the user lifts their finger off the screen, and that generates a touchend event. So using this information, you can use touches to simulate higher-order events, such as swipes. So let's see how to do that in real code.

So here I am in the code. This is my touch_start example and here in my snippets, I've scrolled down to Using Touch Events. And what I am going to do is just copy this code into the document, and then describe to you what it's doing. So we have several lines of code here to copy. So I'll just copy that, go back to the window, and we'll just paste this into the script tag here. So when the window loads, we have a function that just calls handleSwipe, and we are going to handle a swipe on the document's body element, and we want the swipe function to be called-- that's this function right here.

We want the swipe function to be called when the user swipes either left or right. In the swipe function, we are going to receive two arguments: the element that was swiped on, and the direction that the user swiped in, either left or right. So let's go ahead and scroll up to see how this works. So the handleSwipe function is defined up here, and the first argument is the element that we want to watch for swipes on--and that's going to be the document's body--and the function that we want called when a swipe happens.

So before we look at anything else, let's scroll down here to the bottom, and you'll see that we're adding an EventListener for the touchstart event to the element that we were passed-- in this case the document's body. When a touchstart event happens, handleTouchStart will get called. handleTouchStart is right here. When handleTouchStart gets called, we're going to set the contents of the output's div to nothing, and we are going to see if the touches array has a length of 1, because if it has more than 1, that means that more than one finger is on the screen, and this can't be a swipe event.

So if there's only one finger on the screen, we save aside the X and Y position in page coordinates of the first touch. So since there's only one touch, the touch will be contained in the touches array at element 0. So we save away the X and Y coordinates, and then we add EventListeners for touchmove and touchend. We also prevent the default from happening. So in this case, the document is not going to move as the user moves their finger. So the touchmove and touchend events are tracked via trackTouchMove and handleTouchEnd.

So let's see what happens there. So this is trackTouchMove and as the user is moving their finger across the screen, we need to see if the changedTouches.length is not equal to 1, because if the user puts another finger on the screen, that means that they're using more than one finger to move around and it can't be a swipe anymore. So we are going to call the stopTouch function, and we'll get to that in a moment. Now, if the number of fingers on the screen is still 1, we are going to figure out what the deltaX is by taking the current X position of that touch and subtracting off the startX that we had before.

We are also going to figure out what the deltaY is. So we are looking for the change in the X and the change in the Y. We don't want the Y value, in other words the vertical value, to be too big, because in that case, the user is kind of swiping more down than across. So we are going to get the value of the pageY and subtract off the startY that we had saved before. If the swipeDirection, which is a local variable we've defined up here, if swipeDir is null, which means we haven't actually calculated the swipeDirection yet, then we set the swipeDirection to be whatever the deltaX is. And this will be a positive number for the finger moving to the right and a negative number for the finger moving to the left.

Then we call the preventDefault function to keep the touch move from bubbling up the chain and being handled by the document. Now, if we've already got a swipeDirection then we see if the deltaY is greater than the threshold that we've established to stop the touch in progress. and that is right up here, the yThreshhold, and I've set it to 30 pixels. So if the user moves their finger down by more than 30 pixels, then we are just going to cancel the swipe motion.

So in handleTouchEnd, when the user lifts their finger, we are going to stop the touch process, and we are going to see if the absolute value of the deltaX is greater than the xThreshhold. Let's go back up here. So xThreshold is currently 50. So if the user moves their finger more than 50 pixels, we'll say that's good enough to indicate that they want to do a swipe. If it's less than 50 then nothing will happen. So here in handleTouchEnd, we see if they move their finger more than 50 pixels and we call our handler function with the element that was swiped on, and if deltaX is greater than 0--in other words, it's positive--they've swiped to the right; otherwise, they've swiped to the left.

Remember, that function that we got passed in was this guy right here. So in this case, the value of the output divs innerHTML will be set to You swiped plus the direction on element and then the element's tagName. So let's go ahead and see how this works in the code. I am going to save this, and I am going to go to the Simulator. Here's the Simulator. Here's the div right now. I haven't uploaded the changed function to my web server yet, so you can see as I swipe left and right, nothing is happening. So let's go to the Finder, and I am going to copy touch_start into my web server folder and paste.

So now I'll go back to the Simulator. I am going to refresh. Now, as I click and drag and move across and let go, you'll see that I swiped right on the element body, and now I'm going to do back left. Sure enough, it says you swiped left. Now, I am going to try a situation where I moved down by a lot. See how if I move the mouse down by a Y value of more than 30 pixels, we are not registering the swipe event. The movement has to be mostly in the X direction. So you can see even if I'm not perfect about it, I'm still able to like detect swipes as long as the Y value isn't more than 30 pixels.

So just before we leave here, let's go back one more time. So once we are done right here in touchend, remember we called the stopTouch function, and that's this function right here. So we basically just removed the EventListeners on touchmove and touchend and we're all done. So simply by tracking where the touch begins, seeing how it moves across the screen, and then by tracking the touchend, we can simulate a swipe event using the events available to us in the TouchEvent class on the iOS Simulator and an iPhone and other browser that support touch events.

Show transcript

This video is part of

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

46 video lessons · 24375 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.