How to paint an element in screen using javascript?

<div class="body">

<div id="board">

<div id="bat" class="bat"></div>

<div id="ball" class="ball"></div>

</div>

</div>

This is my HTML.

I’ve done CSS For all of them and generated this:

Now, I want the bat to move left and right when I press arrow keys.

window.addEventListener("keydown", function (e) {

switch (e.key) {

case "ArrowLeft":

batDir.x = -1;

batDir.y = 0;

paintBat(batDir.x, batDir.y);

break;

case "ArrowRight":

batDir.x = 1;

batDir.y = 0;

paintBat(batDir.x, batDir.y);

break;

}

})

My goal is to paint the bat at new position. I’m wondering how to do it.

The logic should be

newBatPosition.x=oldBatPosition.x+batDirection.x

newBatPosition.y=oldBatPosition.y+batDirection.y

But what will do the job of painting newBatPosition.x and newBatPosition.y is what I’m not clear of. I’m not using canvas.

Plus, what’ll be the oldBatPosition? I’ve used CSS to paint them. So, I’m wondering how do I get oldBatPosition coordinates as well.

I just made a similar project using tutorial and it’s just sad that I can’t make this project.

We’re still not convinced that this is any more than a deconstruction of something you are trying to copy and make sense of. Please correct me if I’m wrong. Come clean so we can move forward.

no, this one is my own project. I’ve fixed this issue already though…It’s so tough to create own project sir. I feel like giving up.

It’s your own project, but it is obviously coming from some other body of code. Sorry if I just can’t take this seriously as coming from scratch. Anyway, I’ll vacate this or any other topics you start so you won’t have to put up with me.

Can you tell me what are you on about? What other body of code? I wrote this code? I didn’t invent addEventListener rn.

1 Like

I’m just scared to step on toes, and need to be assured we are working with your, from scratch code. If that is truly the case, then I have no problem. That’s where I’m coming from.

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