I have an object called #person that I need to rotate from -180 to 180 degrees with input from a slider. I have the slider working with the input box synced up to show the current angle value and a function I attempted to write but it’s not working. I’m trying to use style.transform. Using bootstrap and jQueryUI in the project, a solution involving those two frameworks instead of standard javascript would also help.
HTML
<label for="angleSlider" class="form-label">Rotation Angle</label>
<form>
<input type="range" class="form-range w-75" id="thetaRange" min="-180" max="180" value="0"
oninput="this.form.thetaInput.value=this.value" />
<input type="number" id="thetaInput" min="-180" max="180" value="0"
oninput="this.form.thetaRange.value=this.value" />
</form>
Javascript
function rotatePerson() {
const person = document.getElementById("person");
var angle = document.getElementById("thetaRange");
person.style.transform = "rotate(angle deg)"
}
2
Answers
The code snippet you provided is almost correct, but there are a couple of issues in the last line of the JavaScript code. Here is the corrected version with an explanation:
Explanation :
1. The
rotatePerson
function selects the element with the ID "person" usinggetElementById
and assigns it to theperson
variable.2. Next, it retrieves the value of the angle from the element with the ID "thetaRange" using
getElementById
and accessing thevalue
property. This value represents the current angle selected on the slider.3. Finally, the code sets the
style.transform
property of theperson
element torotate(" + angle + "deg)
. This dynamically applies the rotation to theperson
element, using theangle
value in degrees obtained from the slider.By calling the
rotatePerson
function whenever the slider value changes, the person element will rotate according to the selected angle.Consider the following jQuery example.
This rotates the element based on the Value of the Range Input on
input
event.