jQuery's draggable and resizable functionality with containment provisions is designed to

I'm struggling to create a resizable and draggable div using jQuery, but it's proving to be quite buggy in its implementation.

Despite finding similar questions, I haven't come across a solution yet.

  • How can I fix the containment bug when using resizable() and draggable() together in jQuery?
  • Resizing a JQuery Draggable element's containment parent while dragging

I've tried different position settings and experimented with the refreshPositions option, but nothing seems to work.

The issues I'm encountering include:

  • Moving the child item quickly (especially in circular movements) often causes it to break out of containment.
  • Dragging the child to the bottom right corner and repeatedly trying to drag it out of the corner gradually breaks the containment further with each iteration.
  • Once the containment is broken, you can continue dragging into that area on subsequent drags.

I've provided a simplified example which reproduces the problem consistently across all browsers, although the demo may not work well in IE 10 and Opera.

$(".child")
    .draggable({
    containment: "parent",
    cursor: "move"
}).resizable({
    handles: "se",
    containment: "parent",
    minHeight: 50,
    minWidth: 50
});

For a complete yet straightforward demonstration, check out this link.

http://jsfiddle.net/jxY8M/

Any suggestions on how to resolve this containment issue would be greatly appreciated.

Answer №1

There seems to be a glitch with the UI draggable feature itself, but it has already been documented here

To address this issue (particularly in the latest version of Chrome), you can try the following solutions:

  1. Add a 5px padding to the parent element, see demonstration here
  2. Add a 5px border to the parent element, see demonstration here
  3. Add a 5px margin to the child element, see demonstration here
  4. Combining any of the above methods for a 5px increase
  5. Add overflow:hidden to the parent element, see demonstration here. Strangely enough, this workaround appears to resolve the issue effectively

Note that the 5px adjustment may vary depending on your specific case. Experimentation may be required to determine the optimal value for your elements. In some instances, I observed that less padding or border width was needed, possibly influenced by the size of the elements. However, I confirmed that the fifth solution worked smoothly in their examples as well.

Answer №2

Utilizing the stop function within the draggable interaction, you have the ability to adjust the resizable parameters effectively. This method proved beneficial for me when encountering similar issues while trying to set containment on both resizable and draggable interactions.

It's worth noting that this approach also works seamlessly with a locked aspect ratio on the resizable interaction.

Example:

<div id="container" style="width: 320px; height: 240px; background-color: #000000;">
    <div id="subject" style="width: 240px; height: 180px; background-color: #ffffff;">
    </div>
</div>

<script type="text/javascript" language="javascript">
jQuery(document).ready(function() {
    jQuery("#subject").resizable(
    {
        aspectRatio: 4 / 3,
        minHeight: 120,
        minWidth: 160,
        maxHeight: 240,
        maxWidth: 320
    }).draggable(
    {
        containment: "#container",
        stop: function(evt, ui) {
            var container = jQuery("#container");
            var subject = jQuery("#subject");

            var containerPosition = container.position();
            var subjectPosition = subject.position();

            var relativeLeft = subjectPosition.left - containerPosition.left;
            var relativeTop = subjectPosition.top - containerPosition.top;

            var maxWidth = (container.width() - relativeLeft) | 0;
            var maxHeight = (container.height() - relativeTop) | 0;

            subject.resizable("option", "maxWidth", maxWidth);
            subject.resizable("option", "maxHeight", maxHeight);
        }
    });
});
</script>

Answer №3

Fixing a containment bug in jQuery when using resizable() and draggable() together: Even though this thread is closed, the solution provided recommends adding position:relative to the parent or container element.

Interestingly, using overflow:hidden did not yield positive results for one user (specifically in Firefox).

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 modifying the function of an Electron application using an external JavaScript file

This is the project structure I envision. https://i.stack.imgur.com/ocRp9.jpg kareljs folder houses an Electron app, and upon running npm start within that directory, a window appears and executes the run method of karel.js when the button Run Karel is ...

Avoiding type errors in d3 v5 axis by using Typescript

I am new to TypeScript and I have some code that is functioning perfectly. I believe if I define a type somewhere, d3's generics will come into play? Within my code, I have an xAxis and a yAxis. Both are the same, but D3 seems to have an issue with t ...

Incorporate the Google Maps API into a React application

I've recently started learning react and I'm currently trying to integrate the Google Maps API into my React application. Within my app, I have a search input field and a designated area for the map located at http://localhost:8080/. My main qu ...

Success callback for tracking conversions on Google

When an ajax call is successful, I am triggering the Google conversion tracking code. Along with tracking the conversion, I also need to change the window location. Is there a method to receive a callback when the conversion tracking is successful, so tha ...

The Frame-context encountered a Script70 Error

I am encountering an issue with Internet Explorer. I have a local website (no webserver, file protocol). The website utilizes frames. I want to use the JQuery tableSort Plugin, so I gather the frame and then select all tables inside the Frame Context. $ ...

Encountering JSON parsing errors while using fetch() POST requests in Express

Currently, I am experimenting with HTTP requests and my main focus is on sending a POST request. The data for this request is coming from an input field and I am using fetch() to send it to a URL on my local host which is set up with express. My goal is to ...

401 Access Denied - Browser extension utilizing Angular JS

In my attempt to implement login functionality within a Chrome extension using Angular, I am consistently encountering a 401 UNAUTHORIZED error. Below is the code snippet I am using: angular.module('chrome-extension') .controller('LoginCont ...

What's the reason behind this file not opening?

When I try to insert this code into files index.html, style.css, and app.js, the page refuses to open. The browser constantly displays a message saying "The webpage was reloaded because a problem occurred." I am using a MacBook Air with macOS Big Sur and a ...

Utilizing a React hook to render and map elements in a function

Can the hook return function be assigned to a render map in React? In this example, we have the socialAuthMethodsMap map with the onClick parameter. I tried to assign the signInWithApple function from the useFirebaseAuth hook, but it violates React's ...

How can I achieve the quickest image loading speed with JavaScript?

If I have a large ecommerce website with 15,000 image elements that need to be added to the HTML, what is the best approach using JavaScript to optimize efficiency and enhance user experience? ...

Tips for customizing a single row in v-data-table? [Vuetify]

My goal is to change the background color of a specific row that contains an entry matching the value of lowestEntry. <v-col cols="8"> <v-data-table :loading="loadEntryTable" loading-text="Searching for data..." ...

Package.json failing to enable NodeJS unsafe-perm functionality

Attempting to execute a npm install command with a preinstall script in my package.json. Despite being aware of it being considered an antipattern, I need to run certain scripts as root. The approach works when adding a .npmrc file with the content unsafe ...

Set the navigation height to fill the entire screen

When the article section expands downwards, the left navigation bar does not extend all the way down. I want the navigation with the background color to expand downwards together with the article text on the right. I attempted to use "height: 100%;" for t ...

What is the process for extracting HTML content using the JavaScript executor?

import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; public class WebDriverExample { public static void main(String[] args) { System.setProperty("webdriver.c ...

How to eliminate the vertical scroll indicators in Material UI's TextField

I'm currently working on customizing the styling of a Material UI textfield and I need to remove the top-down arrows. Below is the code snippet I have so far: const theme = createMuiTheme({ MuiInput: { root: { "&::-webkit-outer-spin-bu ...

Seeking out a particular key within a JSON object and then finding a match based on the id within that key's array - how can it be

Recently, I've been exploring JavaScript and encountering challenges when trying to apply array methods on objects. For instance, I received a fetch response and my goal is to extract the 'entries' key and then utilize the native Array.find( ...

Sneaky spam and ads embedded within Joomla template

Today, while examining the source code of a Joomla site I am developing, I stumbled upon some hidden links that seem to be spam. I have spent an hour searching through various template files but have been unable to locate them. The hidden links in questio ...

Display JSON information in the present moment

I am looking to display only 2 results from a JSON file based on the current time. For example, at 11:00 am today, I want to show only the second and third items. JAVASCRIPT $(data.users).each(function() { var output = "<ul><li>" + this.first ...

In the realm where jQuery meets Django, a mysterious pair of brackets mysteriously appear in my JSON data, causing form validation to

In my Django model, there is a ManyToMany field named images, and I have created a simple ModelForm for this model. I am attempting to send data using jQuery along with a basic UpdateView. The field in the model images = models.ManyToManyField( RawI ...

Tips for guaranteeing that functions within .then() are finished before moving on

Here is an example of using $.when().then(). $.when(setLineDetails(reportId, reportLine)).then(function(data) { console.log("Completed setting line details"); setHeaderDetails(reportId); }).then(function(data) { cons ...