Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

318
Views
JavaScript/jQuery: rotate element on key press (tetris effect)

I want to rotate an element by pressing space bar, like a tetris effect. But so far I can only rotate it once, and the position()method doesn't seem to work like it does when using keys to move sideways. Any help or hint would be appreciated. Here's what I have:

$(document).ready(function() {
  $(document).on('keydown', function(e) {
    var keyCode = e.keyCode;
    var div = $("#div");
    e.preventDefault();

    if (keyCode === 37) div.css("left", (div.position().left - 1) + "px");
    if (keyCode === 39) div.css("left", (div.position().left + 1) + "px");
    if (keyCode === 32) div.css('transform','rotate(-90deg)');

});
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Your rotate property is always -90px. I would have a variable that keeps track of the 'rotation' starting at 0. Then subtracting -90 on every space press. Keep in mind not go over 360, instead reset back to 0.

$(document).ready(function() {
  var rotation = 0;
  $(document).on('keydown', function(e) {
    var keyCode = e.keyCode;
    var div = $("#div");
    e.preventDefault();

    if (keyCode === 37) div.css("left", (div.position().left - 1) + "px");
    if (keyCode === 39) div.css("left", (div.position().left + 1) + "px");
    if (keyCode === 32) {
      rotation -= 90;
      if (rotation < -360)
        rotation = 0;
      
      div.css('transform','rotate('+rotation+'deg)');
    }
  });
});
#div { 
  border: 1px solid #CCC; 
  width: 100px; 
  height: 50px;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div">test</div>

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!