Amazing! We've got our snap game looping and displaying random images. Now we need to detect when a player touches the screen.
1. Create variables for canvas 1 & 2
Our canvas elements have been labelled in our HTML as either 1 or 2. We use 'document.getElementById' to find an element in our HTML document and store the result in a new variable. Watch where we add this code. It should go directly above where we being 'play' function.
How does 'document.getElementById' work?
2. Create event listeners for canvas 1 & 2
'addEventListener' allows us to detect if there is a user touch or click. In the brackets we define when to cause a reaction. In our case we want it to trigger with a touch when the user first touches the screen, so on 'touchstart', rather than 'touchend' or 'touchmove'.
After "touchstart" we tell it what to do when a touch is received. 'playTouch1' and 'playTouch2' are new functions that we'll create next. We could call these anything, but these names are short and clear.
What is 'addEventListener'?
An event listener will literally listen for a specific user event. It could be a touch, in the case of a touch device, or a click in the case of a desktop mouse click.
3. Create playTouch1 & 2
When a touch is detected in a canvas it will trigger one of these functions. Now we're using touch we can't test this on a PC anymore, so we can use an alert popup instead. Get 'View Your App' running on your smart phone or tablet and test the touch events are registering.
How do I view my app on my smart phone or tablet?
On a desktop computer, in Thimble when you publish your app you are given a URL. Just pop this in your phone browser.
4. Prevent Touch Move
When you were testing your apps, you may have found the the browser screen moves up and down. For our game we want to fix the browser in place. Add another 'addEventListener' at the top of script.js. This is targetting the whole document body element and prevents the default behaviour.
What is 'event.preventDefault()'?
Sometimes on a web app we don’t want the default behaviour of, say, a mouse click, to trigger anything. The 'prevent default' function will prevent something from happening (usually a new page loading), which means that we can give the user an even more seamless experience.
Your game is now able to detect touch inputs! You'll have to test this next bit on your smart phone or tablet, as your PC (probably) can't detect touch. Use the URL from the Thimble 'Publish' option to open your app on your phone or tablet. You'll have to republish and refresh your app every time you make a change.
If your game is working properly, when you press the top canvas (player 1) or bottom canvas (player 2) an alert should pop up!