Touch Events - Exercise

Contact Us or call 1-877-932-8228
Touch Events - Exercise

Touch Events

Duration: 15 to 20 minutes.

In this exercise, you will allow users to cycle through book-detail pages by swiping left or right.

  1. Open Events/Exercises/touch.html in a file editor.
  2. Add class bookdetail to each book-detail page.
  3. Write JavaScript code in the head of the document to handle swiperight and swipeleft events on elements of class bookdetail.
  4. In the example code above, we hard coded the first and last pages into our code, changing to the first page (by referencing its id) when the user swiped left on the last page and changing to the last page (by referencing its id) when the user swiped right on the first page. Use jQuery's first and last methods to handle these cases.
  5. Test your code in a mobile browser.

Solution:

Events/Solutions/touch.html

Code Explanation:

We add class bookdetail to each book-detail page, allowing us to limit the pages that will offer users swiping interaction.

$(document).on('swipeleft', '.bookdetail' handles swipe-left events on any div of class bookdetail. We check to see if there is no next bookdetail with if($(this).next('.bookdetail').length == 0). If yes (that is, if none exists), then we use the Pagecontainer's change method to go to the first bookdetail; otherwise, we change to the next bookdetail.

Next