Attributes.html already has two keyboard event triggers. Make these changes:
- delete the second event trigger inside the body opening tag (onkeyup)
- delete the second function changeEmphasisBack completely
- add the event parameter to both of the changeEmphasis event triggers just like it already is in the clickPos event trigger
- add the e variable to the changeEmphasis function (again just like it is in the clickPos function)
Test it and it should work as before apart from not changing the colour back. If not check your error console.
Now change the changeEmphasis function:
- add a new line just under the first line (which starts var) and put this in it: var keyPressed=e.keyCode;
- alert that variable to check that it is working (you should receive a number which is the code for the key you pressed on the keyboard)
- under it create a switch statement (you can copy and adapt the one in switch.html)
- change the first line of the switch statement so that it's condition is keyPressed
- below that delete chicken and the quotes around it and replace that with 82
- do the same for the other two foods (use 71 and 66)
Test the page by pressing r, g and b as well as any one other key on the keyboard. The messages you receive will not relate to what you are doing but they are a good test of the code so far.
The final step is to do something sensible with the three key presses:
- delete or comment out the first alert line (the third line int he function) now that you know the key detection is working
- replace the first alert line inside the switch statement with this: var chosenColour='red';
- replace the other alert lines with similar code but change the colours inside the quotes to green, blue and (for the default case) yellow
- inside the for loop just below delete the word yellow and the quotes around it
- replace that with the chosenColour variable name
Hopefully you can now see what will happen before you try it. Work through the code if not. Then try it to see if you were right (start by pressing g).
If you are using some browsers there will be a problem (Firefox at least at the time of writing). The colours will change but the browser also does something else as well. This is because Firefox assumes that if you type while on a Web page you want to search for what you are typing. To stop it add this line as the first line inside the changeEmphasis function:
e.preventDefault();
Any event in a browser may have a default action. This prevents the default action (start searching for the text) from happening. Otherwise it will change the colour and then do the default as well. You can use this to avoid default pop up menus on right click etc. but think carefully before you do as it might annoy the user. One use is to make the copying of images from a page harder by disabling the ability to right click and copy.