What's the best way to constrain a draggable element within the boundaries of its parent using right and bottom values?

I am currently working on creating a draggable map. I have successfully limited the draggable child for the left and top sides, but I am struggling to do the same for the right and bottom sides.

How can I restrict the movement of a draggable child based on the right and bottom values of its parent element?

     var uright = ui.position.left + 960;  /* 960 represents the height of the map */
     var pright = parentPos.left + 700;    /* 500 is the height of the container */

      if (ui.position.top > parentPos.top) {
     ui.position.top = parentPos.top; // this works correctly
      }
       if (ui.position.left > parentPos.left) {
     ui.position.left= parentPos.left; // this works correctly
      }
    if (uright > pright) {
        uright = pright; // however, this part is not functioning as intended
      }

For reference, here is my working example on jsfiddle

Answer №1

If you're looking to change things up, consider utilizing the getBoundingClientRect method instead of relying solely on the position method. This method returns a text rectangle object that encompasses a group of text rectangles.

rectObject = object.getBoundingClientRect();

The value returned is a TextRectangle object that represents the combined rectangles from getClientRects() for the element, specifically the CSS border-boxes linked to the element.

This returned value contains read-only properties like left, top, right, and bottom, describing the border-box in pixels. The top and left values are relative to the top-left corner of the viewport.

You can extract the top, left, right, bottom values of the element using

rectObject.right, rectObject.top, rectObject.bottom,

For further details, check out: https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect

Alternatively, explore the possibility of incorporating the containment option in jQuery draggable. Link : http://api.jqueryui.com/draggable/#option-containment

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

My current objective is to extract the information from a specific item within a combobox by implementing the following code

alert($("select[name="+this.name+"] option:selected").text()); However, I am not receiving any output unless I explicitly specify the name of the combobox instead of using this.name. This issue may be related to the way quotes are being handled. ...

Is there a way to use JavaScript to import several custom fonts at once?

Is there a way to import a long list of custom fonts as icons using Javascript? I have been obtaining the font list from an API, but importing them one by one with pure CSS using @font-face is time-consuming and difficult to maintain. @font-face { fon ...

show the attributes of an item contained within an array of objects

Hey there! I'm facing an issue with displaying the content of an object on my HTML page using React. So, here's what's happening: I can access the frontend properties in my object array, but when I try to loop through each element and displa ...

Problem occurring with Bulma CDN version 0.8.0 failing to identify the spacing helper

Recently revisited an older project I had started some time ago using the Bulma framework. However, for some reason, the 0.8.0 CDN is not being imported or recognized correctly by the spacing classes. Here's the code snippet I had initially: <link ...

Sharing Axios Response Data in VueJS: A Guide for Parent-Child Component Communication

Can someone please help me with using VueJS and Axios to retrieve API data and pass it to multiple child components? I am trying to avoid accessing the API multiple times in the child components by passing the data through props. The issue I am facing is ...

Causing an element to extend beyond its parent element's boundaries

I have implemented Material Design Lite for creating cards on my website. I encountered an issue where the menu I added to the card only displays within the bounds of the card. I would like it to overflow similar to this example () Here is a link to my fi ...

Maintaining the position of the input cursor when using the arrow up and down keys in AngularJS directive

I am currently developing a custom "typeahead/autocomplete" directive. element.bind("keydown keypress", function (event) { if(event.which === 38 || event.which === 40) { var increment = event.which === 38 ? 1: -1; ... .. ...

Convert HTML to PDF on iOS with our reliable library

Looking for recommendations on an iOS library that can easily convert HTML to PDF. Specifically looking for something with simple functionality. ...

the side panel is positioned under the main content

Can anyone help me figure out why my sidebar is not positioning correctly next to the content on the right side? No matter what I try, it keeps going underneath the content. Here's the CSS code I'm using: body { font: 10pt Calibri, Helvetica ...

What steps should be taken to ensure that my nodeJS server can maintain the identity of a specific user?

Currently, I am in the process of building a mobile application that utilizes Flutter for the front-end and NodeJS for the back-end. Progress has been steady, but I have hit a roadblock while trying to incorporate a lottery feature. The idea is for the se ...

What steps can I take to ensure that my bot disregards any actions taken by other bots?

I need assistance with configuring my bot to ignore certain actions by other bots and prevent logging them. Below is the snippet of my code: let messagechannel = oldMember.guild.channels.find(r => r.name === config.logsChannel); if (!messagecha ...

Creating a dynamic nested list in HTML using JavaScript with data retrieved from a JSON source

I'm trying to generate a dynamic nested ul\li list from a JSON array. IMPORTANT! While I can use jQuery for this transformation, it's in a node.js environment where DOM access is restricted and I must work with a string. The depth of the a ...

Restrict the maximum character count within a TextArea using jQuery

Is there a way to calculate the total number of characters entered in a text area box? For example, if I have a textbox like this: <%: Html.TextArea("Message", "", new { @title = "Enter the Message" })%> I need to limit the input to 160 characters ...

After clicking a button in AngularJS, how can you retrieve one of the two JSON files and store it in a $scope variable?

For instance, You have two JSON files: Json file #1: [{colorname:blue},{colorname:blue}] Json file #2: [{colorname:red},{colorname:red}] Within the controller, there exists a variable called $scope.color In the HTML code, there are two buttons named " ...

Issue encountered while executing npm command: "Module 'npmlog' not found"

Today marks the beginning of my first job, and as I was setting up my development environment on my Mac (OSX) by updating node and npm, something went awry. Whenever I attempt to use npm in my command line (npm init, npm install, etc.), I am confronted wit ...

Incorporating the Material UI App Bar alongside React Router for an enhanced user

For my web development course project, I am venturing into the world of JavaScript and React to create a website. Utilizing Material UI's appbar for my header design, I have successfully incorporated react router to enable navigation on my site. Howev ...

The existence of useRef.current is conditional upon its scope, and it may be null in certain

I'm currently working on drawing an image on a canvas using React and Fabric.js. Check out the demo here. In the provided demo, when you click the "Draw image" button, you may notice that the image is not immediately drawn on the canvas as expected. ...

Unable to fetch data using getJSON method

objecten.js var objectData = [ { image: 'gallery/objecten/bear.jpg', thumb: 'gallery/objecten/bear.jpg', title: 'my first image', description: 'Lorem ipsum caption&apos ...

Transform the data into put and choose the desired item

Here is the data I am working with "dates": { "contract": [ {"id":1,"name":"1 month","value":false}, {"id":2,"name":"2 months","value":true} ] } I want to display this data in a select dropdown on my HTML page. Here is what I have tried s ...

Utilizing JavaScript to assign class names to dynamically created elements from objects

I specialize in javascript and am working on adding the CSS class .is-slideUp to each card__item element created from a data object, in order to achieve a sliding-up animation effect. Although the .is-slideUp class name appears in the console, it does not ...