What is the best approach to keep my dynamic div element within the bounds of the page or screen using jQuery?

My attempt to control the movement of a div using jQuery was unsuccessful as it kept moving off the page.

$(document).ready(() => {
  $(document).on('keydown', function(e) {
    var key = e.which;
    if (key === 37) {
      $('#divResult').animate({
        left: "-=50"
      })
    }
    if (key === 38) {
      $('#divResult').animate({
        top: "-=50"
      })
    }
    if (key === 39) {
      $('#divResult').animate({
        left: "+=50"
      })
    }
    if (key === 40) {
      $('#divResult').animate({
        top: "+=50"
      })
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="divResult"></div>

I am seeking advice on how to prevent the moving div from going outside the boundaries of the page/screen using jQuery.

Answer №1

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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to ensure an element is clickable in WebDriverJS before proceeding?

Is there a way to wait for a WebElement to be clickable in WebDriverJS? I am familiar with waiting for the element to be "visible", but need it to be "clickable". Is there an equivalent of expected conditions in Python binding available in Webdriver Js A ...

Discover the steps for dynamically adding a new row in an Angular application

I am trying to add new rows to a table in Angular, but I'm having some trouble. Initially, there is one empty row, and when I click on the "add new" button after entering details, a new row should be added. I was able to do this using jQuery, but I&ap ...

Encountered Axios GET error, [nodemon] server crashed - currently monitoring for any file modifications before relaunching (using express js, mysql, and react

Initially, my backend was running smoothly until I encountered an issue with axios not being able to retrieve GET data from the backend. In an attempt to resolve this, I changed the port to 8000 in the index.js file, but this caused the backend server to c ...

In order for Jquery's html() and dialog functionalities to work seamlessly, the inclusion of an alert box is imperative

I've encountered a strange issue that I can't explain. For some reason, the code below only works correctly (fetching the HTML from the Action in the controller) if an alert box is displayed before the dialog opens. var ticks; function In ...

Is it possible to include a relative URL with a different port number in a hyperlink?

Is it possible to link to a different port number on the same server without using Javascript or server-side scripting, especially if the hostname is unknown? For example: <a href=":8080">Check out the other port</a> (Note that this example ...

AngularJS bespoke provider leading to "Provider not found" error

I am facing an issue with my custom provider in AngularJS that is supposed to handle global configurations for my application. Despite my efforts, I am unable to properly inject this provider as AngularJS keeps throwing an "Unknown provider" exception. Thi ...

JavaScript (Create a button that toggles the visibility of an element)

I have implemented a hamburger menu that transforms into an x when clicked. I am looking to modify it so that clicking on the hamburger opens the menu, and clicking on the x closes the menu. Below is the code I have been working with: <!DOCTYPE html&g ...

Overlapping dynamic content causing CSS nested scrollbars to clash at full width of 100%

Displayed below is a layout with two nested divs, both featuring automatic vertical scrolling. Is there a CSS technique available to show the inner scrollbar while maintaining the inner div at 100% width? https://i.stack.imgur.com/HSKHH.png div { ba ...

The next and previous buttons on the JQuery UI datepicker are related to only one ancestor. When using $(e.target).parents(), it will only return a

Unfortunately, my reputation isn't high enough to post my own answer just yet. However, I wanted to share it before wasting more people's time: I finally figured out why I was not getting all the expected ancestors: The JQuery datepicker actuall ...

Tabular Bootstrap 4 elements nested within a dropdown menu

I am currently utilizing a bootstrap 4 dropdown menu that includes tabs within it. Below is the codepin for reference: I came across this link that provided a helpful solution to prevent the dropdown menu from closing when clicked inside: Avoid dropdown m ...

Discovering all asp.net elements with a customized suffix through the power of jQuery

Is there a way to target all asp.net elements with a suffix _val using dynamic client ID, instead of static client ID? The usual approach is: $('div[id$="_val"]') We also know how to select individual elements: $(document).ready(function () { ...

Angular: Understanding Render Delay Caused by *ngIf and Expression Changes from Filters

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'. Encountering the above error in the console. In my code, I have filters that control ...

Presenting a Random Term from an Array in Dual Locations

<input type="button" id="btnSearch" value="Search" onclick="myFunction();" /> <div id="message"> <p></p> </div> <br> <div id="message"> <p></p> </div> <script type="text/javascript"&g ...

Avoiding do/while loop

Hey everyone, I'm currently working on an algorithm designed to remove concrete branches, similar to Depth-First Search (DSF), from a NodeTree. Basically, the algorithm checks if a specific node is acting as a parent for other nodes; if so, it grabs t ...

What is the best way to create an object using a string value as a reference?

I am seeking a way to efficiently utilize a string within an API factory to dynamically create the appropriate object from a class. Here is the script: import StoryApiService from './story' import AssignmentApiService from './assignment&apo ...

Activate real-time highlighting by clicking on the search button

I created a simple program that searches for a value within a div and displays the first location of the word. However, I am looking to enhance it by highlighting all repeated locations of the searched word after pressing the search button. <html> & ...

I wonder which Material Design repository is the source of this library

I am attempting to replicate the CSS style used in this particular Material Design-inspired web application: https://i.stack.imgur.com/utalx.png After exploring Materialize CSS and MUI, I have not been able to pinpoint the exact framework responsible for ...

What happens when the next button is clicked without any items selected?

I am working on a dynamic HTML page where a section changes based on user-selected options. Here is the part that displays the options: <div class="form-group-lg"> @foreach (var response in Model.ListResponses) { ...

Is there a different technique I can use to display an axios response within a v-if statement? Any other methods I should

As a newcomer to Vue.js, I'm struggling with certain concepts even after extensively reading the documentation! My goal is to show a glyphicon when my API call returns true. However, since the call is within a for loop iterating over multiple items, ...

What is the best method for incorporating startbootstrap into a react component?

Seeking assistance with incorporating a StartBootstrap template into my React component. The template can be found at this link. Here is the envisioned page layout: https://i.sstatic.net/bpQyE4Ur.png To ensure proper rendering of the template, I have org ...