JSFiddle - React, Tailwind, and code Playground
by whelkaholism
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img id="spider" src="https://vignette.wikia.nocookie.net/minecraftpocketedition/images/8/84/Spider.png"/>
<div id="messages"></div>
CSS
#spider {
position: absolute; /* Make the spider go exactly where you tell it! */
left: 0;
top: 0;
}
#messages {
position: fixed; /* Make this messages window stay put */
width: 200px;
height: 100vh; /* Short for 100 percent of vertical height - or in other words, fill from top to bottom! */
right: 0;
top: 0;
background: rgba(0, 0, 0, 0.5);
color: #ffffff;
font-family: monospace;
font-size: 10px;
padding: 10px;
}
JavaScript
/*
This is how you start a jQuery app, it makes sure you only start
doing things when the whole page is loaded.
*/
jQuery(
function()
{
/*
This tells the browser to catch all key presses on the page and do things
with them.
*/
$('body').on('keydown',
function(event)
{
/* Call the helper function we set up below */
addMessage('Key code ' + event.keyCode + ' pressed!');
/*
See what key was pressed, and call a movement helper function to do that action.
*/
if(event.keyCode == 37) /* LEFT */
goLeft();
else if(event.keyCode == 38) /* UP */
goUp();
else if(event.keyCode == 39) /* RIGHT */
goRight();
else if(event.keyCode == 40) /* DOWN */
goDown();
}
)
}
)
/*
MOVEMENT helper functions ========================================================
*/
/*
TRY CHANGING THESE! WHAT DO YOU THINK WILL HAPPEN? WHY?
*/
var MOVEMENT_AMOUNT = 20;
var MOVEMENT_SPEED = 100;
function goLeft()
{
var current_left = $('#spider').position().left;
$('#spider').animate({ left: current_left - MOVEMENT_AMOUNT }, MOVEMENT_SPEED);
}
function goUp()
{
var current_top = $('#spider').position().top;
$('#spider').animate({ top: current_top - MOVEMENT_AMOUNT }, MOVEMENT_SPEED);
}
function goRight()
{
/*
Question: Why do you think that we are using the spider's left, not its right?
*/
var current_left = $('#spider').position().left;
$('#spider').animate({ left: current_left + MOVEMENT_AMOUNT }, MOVEMENT_SPEED);
}
function goDown()
{
/*
Question: Why do you think that we are using the spider's top, not its bottom?
*/
var current_top = $('#spider').position().top;
$('#spider').animate({ top: current_top + MOVEMENT_AMOUNT }, MOVEMENT_SPEED);
}
/*
Helper function to add a message ==================================================
*/
function addMessage(msg)
{
/* Get all the current messages so we can...