To ensure that your content stays within the boundaries of the window, you can use $(window).width()
and $(window).height()
to compare with the position of the div. Additionally, I recommend using event.Key
as the native event.which
(not the jQuery version) is now deprecated.
let animationInProgress = false;
const debounceTime = 100; // time in milliseconds for debouncing
$(document).on('keydown', (e) => {
if (animationInProgress) return;
animationInProgress = true;
setTimeout(() => {
animationInProgress = false;
}, debounceTime);
const key = e.key;
const $divResult = $('#divResult');
const currentPosition = $divResult.position();
const pageWidth = $(window).width();
const pageHeight = $(window).height();
const divWidth = $divResult.width();
const divHeight = $divResult.height();
const step = 50; // adjust this value to your preference - it was set to 50 in the example provided;
let newLeft, newTop;
if (key === "ArrowLeft" && currentPosition.left > 0) {
newLeft = Math.max(currentPosition.left - step, 0);
$divResult.animate({
left: newLeft
});
}
if (key === "ArrowUp" && currentPosition.top > 0) {
newTop = Math.max(currentPosition.top - step, 0);
$divResult.animate({
top: newTop
});
}
if (key === "ArrowRight" && currentPosition.left + divWidth < pageWidth) {
newLeft = Math.min(currentPosition.left + step, pageWidth - divWidth);
$divResult.animate({
left: newLeft
});
}
if (key === "ArrowDown" && currentPosition.top + divHeight < pageHeight) {
newTop = Math.min(currentPosition.top + step, pageHeight - divHeight);
$divResult.animate({
top: newTop
});
}
});
#divResult {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top: 50%;
left: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="divResult"></div>