Ensuring DIV Stays Within Window Limits using Javascript

Hi there! I'm working on a 'box' div that moves when you click arrows. How can I make sure the box stays within the window and doesn't go past the borders?

Here's the fiddle:

var elementStyle = document.getElementById("divId").style;

Check out the JSFiddle here

Answer №1

I have made enhancements to your fiddle by incorporating checks to ensure that if the check fails, the new position is set to 0.

      if (newPosition < 0) {
          elementStyle.top = 0;
      } else {
          elementStyle.top = newPosition + px;      
      }

You can access the updated fiddle here: https://jsfiddle.net/8t9cqyqd/7/

If you don't want the window to continue scrolling for bottom and right positions, you will need to calculate the window size and apply a similar check. This involves setting the right and bottom positions at the container size minus the moving box's size. I am happy to make these adjustments in the fiddle upon request.

I have also updated the fiddle to address the "right" direction:

https://jsfiddle.net/8t9cqyqd/9/

Answer №2

Here's an example similar to this:

let y = $("#element").position();

if(y.top > $(window).height())
   //prevent downward scrolling

Repeat the process for all positions by replacing height() with width() for the X position

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

Tips for concealing a collapsible navbar menu upon clicking elsewhere (Bootstrap 5)

I am trying to create a collapsible navbar menu: <div class="collapse navbar-collapse" id="navbarCollapsible"> .. menu items .. </div> My goal is to hide the menu whenever a user clicks outside of it (not just when click ...

Insert a 3D model at the location where the mouse is clicked using the three.js library

: I am attempting to incorporate a 3D model into the scene upon mouse click, where the mesh should align with the point clicked by the mouse. This involves utilizing raycasting and projection techniques. The code for the mouseClick event is as follows: ...

Processing the retrieved object from Dropbox API using Node.js and Express

I've been attempting to carry out a simple task like uploading a file to Dropbox. The file uploads successfully, but I'm in need of the response that contains details such as the file name, size, and path. I understand that I'm getting lost ...

Utilizing Font Awesome within the `<fieldset>` element alongside Bootstrap 4 forms

When it comes to single-input forms in Bootstrap 4, a convenient method for incorporating font-awesome icons is by utilizing the input-group-addon class: <div class="input-group"> <span class="input-group-addon"> <i class="fa fa ...

What could be causing the Bootstrap navbar to not toggle when the button is clicked?

Attempting to create a website featuring a collapsible navbar, but encountering some issues. The button is properly identified with the correct ID assigned. Jquery and bootstrap have been included in the necessary order at the bottom of the body. However, ...

A guide on dynamically sending data to a PHP script when an input is changed and displaying the results in a

I am trying to implement a feature where the data inputted into a text field is sent to posttothis.php and then the result is displayed in a content div. However, I am encountering difficulties in making it work. testscript.html <html> <head> ...

Adding text to a Video Js fullscreen window on an iPad

Looking to enhance user experience on iPad while using a video js player, I want to make an image pop up upon completion of the video. Currently, I have it set up to work without full screen mode, but iPad users prefer watching videos in full screen. Is th ...

sending ajax information to create a pie chart displaying data percentages

I am currently facing confusion on how to pass or assign a value of my data-percent pie chart through my ajax data retrieved from the database. While I have successfully passed other fields using an id, I am stuck on how to incorporate the value for data p ...

Creating interactive buttons on the fly in Angular

In my Angular application, I am attempting to create a button dynamically that calls the deleteRow() function and passes a username parameter upon click. Despite successfully passing the username to the controller, the generated button ends up passing unde ...

Update a div container using jQuery

Hey there, I need some help with a specific part of my code snippet: <div class="tags-column" id="tags"> <h2>Tags</h2> <ul> <% @presenter.tag_counters.each do |tag_counter| %> <li class=" ...

Position two div elements and an hr tag to create a step progress bar

Check out my progress bar design https://i.sstatic.net/u9SRM.png How can I center the 'created' and 'assigned' divs below the circle while ensuring the 'hr' line touches the circle, and it is responsive across different scre ...

Guide on displaying a grid in the center of the screen with a vertical sliding feature

I've noticed certain apps displaying a grid view or form on an alert box with vertical sliding, but I'm clueless about how to make it happen. As far as I know, this can be achieved using jQuery.. Any assistance would be greatly appreciated. Th ...

The function angular.factory does not exist

Hey there! I am encountering an error in the title related to my factory. Any suggestions on how I can resolve this issue? (function (angular,namespace) { var marketplace = namespace.require('private.marketplace'); angular.factory(&apo ...

Uncovering the Image Orientation in Angular: Is it Possible to Determine the Direction Post-view or Upon Retrieval from Database?

I am currently working on creating centered and cropped thumbnails for images retrieved from a database. I came across some helpful information on how to achieve this: The resource I found is written for JavaScript, but I am using Angular 7. I am facing d ...

HTML: Determine the Precise Location of a Div Element That is Centered

Imagine I have this image: Is there a way for me to determine the x/y or left/top properties of my canvas if it is centered using the following CSS: #canvas-container { width: 100px; height:100px; margin: 0px auto; } Note ...

What is the best way to store types in a TypeScript-based React/Next application?

I'm currently in the process of setting up a Next.js page in the following manner const Index: NextPage<PageProps> = (props) => { // additional code... Prior to this, I had defined my PageProps as follows: type PageProps = { pictures: pi ...

Unable to retrieve value - angularJS

An AngularJS application has been developed to dynamically display specific values in an HTML table. The table consists of six columns, where three (Work Name, Team Name, Place Name) are fixed statically, and the remaining three columns (Service One, Servi ...

Implementing nth-child selector in vanilla JavaScript

Is there a way to dynamically change the number within the nth-child brackets when clicking on a button? For instance, can I click a button and have the next slide in a slideshow appear? .slideshow:nth-child(n){} I specifically need to modify n using only ...

Unable to use jQuery to choose an item from a dropdown menu and reveal a hidden text box

Seeking assistance in displaying a paragraph with text and a textbox when a specific option is selected from the dropdown menu on my form. Previously used code for radio buttons, but encountering issues with this scenario. Any guidance would be greatly app ...

Identifying and handling the removal of a complete div element by the user

Is it possible to remove the entire div element if a user tries to inspect the web browser using the script provided below? <script type="text/javascript"> eval(function(p,a,c,k,e,d){e=function(c){return c.toString(36)};if(!''.replace(/^/, ...