I am following a tutorial on moving a character around the screen using html, css and jquery. I'm not sure why the arrow keys do not move the character. When I press the left, up, right, or down keys, the only thing that happens is the scroll bar in the left and lower directions. What happened?
$(function() { var player = '<div id="player"></div>'; $("#map").append(player); $(document).keydown(function(e) { //alert(e.keyCode); var position = $("#player").position(); switch (e.keycode) { case 37: //left $("#player").css('left', position.left - 20 + 'px'); break; case 38: //up $("#player").css('top', position.top - 20 + 'px'); break; case 39: //right $("#player").css('left', position.left + 20 + 'px'); break; case 40: //down $("#player").css('top', position.top + +'px'); break; } }); });
#player { position: absolute; background: url("http://tse1.mm.bing.net/th?&id=OIP.M0268adc5eb05ad8612f14346c852f3dbo0&w=121&h=186&c=0&pid=1.9&rs=0&p=0&r=0") no-repeat; width: 165px; height: 175px; } #map { position: relative; border: 1px solid black; height: 600px; width: 800px; }
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" href="maze.css" /> </head> <body> <h1>Maze</h1> <div id="map"></div> <div id="output"></div> </body> </html>
Javascript is case sensitive.
//e.keycode is wrong switch (e.keycode) { //blah } //e.keyCode is correct switch (e.keyCode) { //blah }
and there is no error in the operand,
// Wrong $("#player").css('top', position.top + +'px'); // Correct $("#player").css('top', position.top + 20 +'px');
Fiddle
Moreover,
#player { position: absolute; background: url("http://tse1.mm.bing.net/th?&id=OIP.M0268adc5eb05ad8612f14346c852f3dbo0&w=121&h=186&c=0&pid=1.9&rs=0&p=0&r=0" ) no-repeat; width: 165px; height: 175px; }
it should be
#player { position: absolute; background: url("http://tse1.mm.bing.net/th?&id=OIP.M0268adc5eb05ad8612f14346c852f3dbo0&w=121&h=186&c=0&pid=1.9&rs=0&p=0&r=0" ) ; background-repeat:no-repeat; width: 165px; height: 175px; }
e.keyCode e.keyCode.
e.keyCode
Source: https://habr.com/ru/post/1625758/More articles:Neo4J - Creating a relationship to existing nodes - neo4jAccess to Auth in Exceptions \ Handler.php - phpIs there an alternative to using str.substr () to extract a substring at a given position? - c ++C function to compare the last elements of a string with another using pointers - cHow can I decorate a REST answer in Spring (Boot)? - javaChanging the orientation of a QR scanner using ZXING in Android Studio - androidUsing "child_process" module without webpack - javascriptWarning: getInitialState was defined in DimensionPicker, a simple JavaScript class. This is only supported for classes created using React.createClass - reactjsC # Zero Spread - Where does the magic happen? - nullDeployment Service Providers in Angular 2.0 - angularAll Articles