• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Limit variable


New Coder
Hi, I'm making a website with a picture of a bed mattress that is turning right/left. I've made a js script to rotate the picture 5 degrees forward when the right-arrow button on a keyboard is pressed and -5 degrees back when the left-arrow button is pressed. However, it is possible to completely flip the bed, which is not in my interest, so I was wondering if it was possible to somehow limit the rotation in the interval -20 deg ; 90 deg?

Heres the code for the js:

    var current_rotation = 0

    function rotate(grader) {
        current_rotation = grader + current_rotation;
        document.getElementById("madras").style.transform = 'rotate(' + current_rotation + 'deg)';
        console.log("Der er blevet roteret!");

    document.addEventListener('keydown', function(event) {
        if (event.keyCode == 39) {
        } else if (event.keyCode == 37) {
    }, true);


Thanks in advance,


Active Coder
Change your rotate function to something like this:

function rotate(grader) {
    let min = -20;    // Minimum Degrees
    let max = 90;    // Maximum Degrees
    let new_rotation = grader + current_rotation;

    if(new_rotation < min || new_rotation > max) {
        console.log("Cannot rotate, angle out of bounds");
    else {
        current_rotation = new_rotation;
        document.getElementById("madras").style.transform = 'rotate(' + current_rotation + 'deg)';
        console.log("Der er blevet roteret!");