Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member
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.
Get unlimited access to all courses for just $25/month.Become a member
82 Video lessons · 98584 Viewers
61 Video lessons · 85881 Viewers
71 Video lessons · 69763 Viewers
56 Video lessons · 102070 Viewers
Access exercise files from a button right under the course name.
Search within course videos and transcripts, and jump right to the results.
Remove icons showing you already watched videos if you want to start over.
Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.
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.
Your file was successfully uploaded.