JSFiddle - React, Tailwind, and code Playground
by Roko
HTML
<b>Use ← → arrow keys to move #box.</b><br>
#parent width is 100px.
#box width is 20px.<br>
Let's limit box movement (left position) from 0 to 100-20:
<div id=parent>
<div id=box></div>
</div>
CSS
#parent {
position:relative;
margin: 0 auto;
width:100px;
border:2px solid red;
}
#box{
position:relative;
width:20px; height:20px;
background: blue;
}
JavaScript
var box = document.getElementById("box"),
x = 0; // Box initial position
// Restrict number to range
function clamp(min,max, val) {
return Math.min(Math.max(min, +val), max);
}
document.addEventListener("keydown", function(event) {
var key = event.which; // (IE9+)
if(key===39) { // Right Arrow
x = x+5;
}else if(key===37) { // left arrow
x = x-5;
}
// At this point x can go below 0 or over 100,
// let's clamp the x value to that range
x = clamp(0, 100-box.clientWidth, x);
// Apply new box position:
box.style.left = x+"px";
});