Dodger game with eventListener

Hello everyone :raised_hand:
I’m practicing eventListener() with This dodger game
how ever when I try to move the dodger to the right side without going off the container(The dodger width is 40px) it doesn’t work here is my codepen
any hint will be greatly appreciated .

What do you want it to do?

Your html has error. Its codepend related. Leave only this part of the html:

<div id="game">
    <div id="dodger" style="bottom: 0px; left: 180px;"></div>
</div>

In codepen, the html tag, the head and the body are already defined. You already write inside the body. By default, the styles and the javascript are linked to the html you write. If you want to input something in the “document” head, you can directly click the html settings button and write it there.
Since for both left and right movement, you utilize same event(“keydown”), you can directly move those move left and right functions in the same event listener and execute the appropriate one, when the correct key is pressed, just how you do.
You can call dodger.getBoundingClientRect(), which will give you some positioning stats of the element you call it on(your dodger rectangle). Using those values, you can determine when for example, the move right function should not be executed(when its +200 px from dodger starting position, in your case, or something alongthe lines). You can composite the condition many ways, so it fits your purpose.
Another option, without checkign the element position is to try and set some global state of your dodger, to estimate how much it has moved left and right from its initial position and put limits based on it. Everytime you move left, you will add the movement value to the left(-) and everytime you move right, you add it to right(+) and not let it go over 200px left or right

Thanks a lot @Sylvant dodger.getBoundingClientRect() this method helped me to determine when the rectangle should stop, I’ve added `

 if (left < 359.5 ) {   dodger.style.left = `${left + 1}px`  
` 

to the second function and it worked,this is the updated version

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.