Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I with the use of JavaScript and CSS transform property make an object move 20px and roll 180deg with each press of any keyboard button?

Hello I have to make and object (in my case a circle) move 20px and roll 180 deg each time any key on my keyboard is pressed.

Can anybody help med with this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

// declare initial values
let pos = 0
let rot = 0

// grab the element
const circle = document.querySelector('.circle')

// add listener for keydown event
document.addEventListener('keydown', () => {
  // increase values
  pos += 10
  rot += 10

  // use translate and rotate with the current values
  circle.style.transform = `translateX(${pos}px) rotate(${rot}deg)`
})
.circle {
  border-radius: 50%;
  height: 200px;
  width: 200px;
  background: red;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="circle">text</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading