# How to paint an element in screen using javascript?

**URL:** <https://forum.kirupa.com/t/how-to-paint-an-element-in-screen-using-javascript/656235>\
**Category:** Uncategorized\
**Created:** [January 11, 2023, 10:38am UTC](https://forum.kirupa.com/t/how-to-paint-an-element-in-screen-using-javascript/656235 "2023-01-11T10:38:34Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![polaryeti](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/polaryeti/32/19283_2.png) [@polaryeti](https://forum.kirupa.com/u/polaryeti)\
**Post date:** [January 11, 2023, 10:38am UTC](https://forum.kirupa.com/t/how-to-paint-an-element-in-screen-using-javascript/656235/1 "2023-01-11T10:38:35Z")

</div>

```auto
<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:

 ![](https://canada1.discourse-cdn.com/flex011/uploads/kirupa/original/3X/c/d/cdb5a9557540a0eb10de8aaa152a68b01d6ce839.png)

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

```auto
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

```auto
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.

https://codepen.io/pelko/embed/preview/jOpBmPN?default-tabs=js%2Cresult&height=300&host=https%3A%2F%2Fcodepen.io&slug-hash=jOpBmPN

---

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [January 11, 2023, 5:47pm UTC](https://forum.kirupa.com/t/how-to-paint-an-element-in-screen-using-javascript/656235/2 "2023-01-11T17:47:50Z")

</div>

If you are not using Canvas, you can use CSS to move the elements. Take a look at the first example here:

> **[Creating Animations in JavaScript](https://www.kirupa.com/html5/animating_in_code_using_javascript.htm)**
>
> Take full control over your animations by learning how to create them entirely in JavaScript.

Unless you are going for an 8-bit “stuttering” effect, having all of your move code inside a requestAnimationFrame loop can help you create smoother animations!

🙂
