Search code examples
javascripthtmlfunctioninputreturn

Js rotate from input


I want to rotate a div from input so when I change the number to 20 for example, it'll rotate my div with 20deg

.style.transform = “rotate(“n” + “deg” did not work for me

function fs(n) {
  n = document.querySelector('input').value;
  document.getElementById('bb').style.transform = "rotate(".push(n)")";
  console.log(n + "deg");
}
<input type='number' placeholder='ttt' oninput='fs()'>
<div class='bb' id='bb'></div>
<button onclick='fs()'>Click</button>


Solution

  • Quite a few issues.

    It helps to make the div position absolute and then create the actual css statement

    You want rotate(ndeg) so you need to create ndeg correctly. That is EITHER concatenation "rotate("+n+"deg)" OR template literals

    `rotate(${n}deg)`
    

    function fs(n) {
      n = document.querySelector('input').value;
      document.getElementById('bb').style.transform = `rotate(${n}deg)`;
    }
    #bb { position:absolute }
    <input type='number' placeholder='Rotation in deg' oninput='fs()'>
    <div class='bb' id='bb'>MY DIV</div>