html – javascript moving a div left and right

So i made this mini game, and I want that my “player” named div to move to left and right inside of the “game” div. but I’m stuck, can someone help me? I think my error is inside of the javascript file… Also if my “player” div moves, will my “gun” div move with it too?


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <link rel="stylesheet" href="style.css">
    <p>Galaxy Invaders</p>
    <div class="game">
        <div id="player">
            <div id="gun">
                <div id="bullet"></div>
        <div id="enemy"></div>
    <script src="js.js"></script>

my CSS

    margin: 0;
    padding: 0;
    background-color: mediumblue;
    height: 800px;
    overflow: hidden;

    font-size: 48pt;
    color: black;
    font-family: fantasy;
    font-weight: bold;
    position: relative;
    left: 300px;
    top: -50px;


    width: 800px;
    height: 500px;
    position: center;
    border: 14px solid darkblue;
    border-radius: 5px;
    margin-left: 300px;
    margin-top: -100px;
    background-color: black;


    height: 20px;
    width: 40px;
    background-color: firebrick;
    border-radius: 2px;
    position: relative;
    top: 470px;
    left: 400px;

    position: relative;
    height: 40px;
    width: 10px;
    background-color: firebrick;
    top: -20px;
    left: 15px;
    border-radius: 2px;


    position: relative;
    background-color: darkorange;
    width: 8px;
    height: 20px;
    top: 0;
    left: 1px;
    animation: shoot 0.7s linear;


@keyframes shoot {
    0%{top: 0px;}
    100%{top: -470px;}

And finally my javascript file:

let modifier = 50;
let player = document.getElementById('player');

window.addEventListener('keydown', (event) => {
    const { style } = player;
    switch (event.key){
        case 'ArrowRight':style.left = `${parseInt(style.left) - modifier}px`;break;
        case 'ArrowLeft':style.left = `${parseInt(style.left) + modifier}px`;break;


Source link

Latest articles

Related articles

Leave a reply

Please enter your comment!
Please enter your name here