How can I restrict the draggable space? It is only working on the top and left sides, but I want to disable it on the right and bottom

Attempting to prevent the draggable items from overflowing beyond the body.

Succeeded in limiting movement on the top and left sides.

Encountering difficulty restricting motion on the right side and bottom.


e.pageX -= e.offsetX;
e.pageY -= e.offsetY;

// horizontal constraint
if (e.pageX - dragoffset.x < 0) {
    offsetX = 0;
} else if (e.pageX + dragoffset.x > document.body.clientWidth) {
    offsetX = document.body.clientWidth - e.target.clientWidth;
} else {
    offsetX = e.pageX - dragoffset.x;
}

// vertical constraint

if (e.pageY - dragoffset.y < 0) {
    offsetY = 0;
} else if (e.pageY + dragoffset.y > document.body.clientHeight) {
    offsetY = document.body.clientHeight - e.target.clientHeight;
} else {
    offsetY = e.pageY - dragoffset.y;
}   

el.style.top = offsetY + "px";
el.style.left = offsetX + "px";
}

Experiencing erratic behavior with draggable divs during movement. They only stop accurately at the right and bottom when the text inside is selected.

Answer №1

Discover a drag-and-drop library that offers the unique feature of restricting movements of draggable elements

Check out the drag and drop library here!

By default, this library limits element movements within a specified container, taking into consideration the size of the element.

import { Draggable } from 'dragee'
new Draggable(element, { container: document.body })

Furthermore, you can customize movement restrictions using your own bound function

import { Draggable, BoundToRectangle, Rectangle } from 'dragee'
new Draggable(element, { 
    bound: BoundToRectangle.bounding(Rectangle.fromElement(document.body, document.body))
})

The BoundToElement class defines the specific restrictions required

class BoundToRectangle {
  constructor(rectangle) {
    this.rectangle = rectangle
  }

  bound(point, size) {
    const calcPoint = point.clone()
    const rectP2 = this.rectangle.getP3()

    if (this.rectangle.position.x > calcPoint.x) {
      (calcPoint.x = this.rectangle.position.x)
    }
    if (this.rectangle.position.y > calcPoint.y) {
      calcPoint.y = this.rectangle.position.y
    }
    if (rectP2.x < calcPoint.x + size.x) {
      calcPoint.x = rectP2.x - size.x
    }
    if (rectP2.y < calcPoint.y + size.y) {
      calcPoint.y = rectP2.y - size.y
    }

    return calcPoint
  }
}

To determine the size of an element, use the following calculation:

let width = parseInt(window.getComputedStyle(element)['width'])
let height = parseInt(window.getComputedStyle(element)['height'])

Consider utilizing the translate3d property for movements instead of traditional left and top positions for improved efficiency

Answer №2

It appears that when the draggable element is a DOM element, it adjusts the width and height of the body as it moves right or down. This alteration in body size suggests that relying on the body size may not be ideal. Instead, consider utilizing window.width and window.height, or similar values, to confine the area within boundaries unaffected by the draggable item. I hope this suggestion proves helpful.

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

Switching JButton Icon when Clicked

I am working on developing a Java JFrame Application that resembles Minesweeper but with some unique rules and objectives. Currently, I have set up a grid of JButtons in a 12x12 layout using a JButton 2D array. My goal is to change the image displayed on ...

Why is the 'a' element not clickable after the AJAX complete function has executed in JavaScript?

I have a small question regarding my use of AJAX. Everything is working fine, but after the AJAX request completes, I am trying to change the element attributes such as backgroundImage dynamically. Although this process works correctly, the element that wa ...

Error: doc.data().updatedAt?.toMillis function is not defined in this context (NextJs)

I encountered an error message while trying to access Firestore documents using the useCollection hook. TypeError: doc.data(...)?.updatedAt?.toMillis is not a function Here is my implementation of the useCollection Hook: export const useCollection = (c, q ...

React Router Error: Hook call invalid. Remember to only use hooks inside the body of a function component

I am having an issue with my React app that uses react router. In Box.js, I am attempting to access the URL parameters but I am encountering the following error message: Invalid hook call. Hooks can only be called inside of the body of a function component ...

Creating a custom directive in AngularJS that utilizes an event listener

I am currently working on designing a custom directive that includes a text box. When a user clicks a button, the text box should expand and become focused. If the user then clicks away from the expanded text box, it should minimize, disappear, and display ...

Using Jquery to find the class that matches the current element

Is it possible to select a specific div by its class when there are multiple divs sharing the same class and triggering the same function on button click? I only want to target the class where $(this) is located. I've experimented with .parent, .chil ...

Ways to organize the information within the Ul and Li elements

I need help sorting the data within <ul> and <li> elements using jQuery. Below is a snippet of my code: <ul id="rootUl"> <li> <div id='title'>MSFT</div> <div id='price'>230</d ...

How can Selenium and Java be used to obtain a dropdown menu with selectable options?

How can I use Java in Selenium to retrieve a complete list of options available for selection in a dropdown menu? ...

Is it possible for Typescript to resolve a json file?

Is it possible to import a JSON file without specifying the extension in typescript? For instance, if I have a file named file.json, and this is my TypeScript code: import jsonData from './file'. However, I am encountering an error: [ts] Cannot ...

Is there a way to enable drag and drop functionality on a dynamically created table using AJAX?

I have been successfully using the TableDnD plugin for drag and drop functionality on table rows. However, I am now facing an issue with dynamically generated tables via AJAX. The code doesn't seem to work as expected when it comes to drag and droppin ...

When assigning JSON to a class object, the local functions within the class became damaged

This is a demonstration of Object Oriented Programming in JavaScript where we have a parent Class called Book with a child class named PriceDetails. export class Book { name: String; author: String; series: String; priceDetails: Array<Price> ...

Experiencing a null value?

While I was working on my project, I encountered an issue with the getImageList() method where it is returning a null value even after passing the correct values. I tried logging to verify the problem. Could someone please take a look at it? Below is the ...

An issue occurred during the hydration process, causing the entire root to switch to client rendering since the error occurred outside of a Suspense boundary

I've started seeing some errors and warnings: Error: An error occurred while hydrating. Since it happened outside of a Suspense boundary, the entire root will switch to client rendering. Error: Hydration failed due to initial UI not matching what was ...

I am having trouble getting event handlers to work with a group of buttons in JavaScript

I'm facing a problem where I'm attempting to add event handlers to buttons stored in an array. Upon clicking a button, it should trigger a function, but for some reason, it's not working and I can't seem to identify the issue. Below is ...

Unable to receive notifications within an AngularJS service

<!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <body> <div ng-app="canerApp" ng-controller="canerCtrl"> <button ng-click="click()"> ...

Establishing the preset values for Material-UI toggle button group

I utilized the Material UI library to implement a button toggle widget for selecting options. Check out my codesandbox project here - https://codesandbox.io/s/50pl0jy3xk The user can interact by choosing a membership type: adult, child, or infant. Option ...

Any recommendations for building HTML in an iOS UIWebView?

When using a UIWeb view, how can I create HTML content? For example, I have some header html code. Then, I would like to include a JavaScript script and pass data to it. Once the JavaScript is injected, I want to add the remaining HTML content from a .html ...

``Emerging Challenge in React: Ensuring Responsive Design with Fixed Positioning

I'm currently encountering a challenge with my React application. I've developed a website using React that includes a component named CartMenu, which is integrated within another component called Products. The issue arises when I utilize the de ...

Transferring information between Vue.js components via data emissions

Greetings from my VueJS Table component! <b-table class="table table-striped" id="my-table" :items="items" :per-page="perPage" :current-page="currentPage" :fields="fields" @row-clicked="test" lg >< ...

Tips on how to showcase it to cover a wide area

I'm having trouble figuring out how to display the output in a span element. Every time I try, I just get a blank result, and when I alert the txtNumber variable, I see "object html span element" in the alert message. <span id="displayQty"> num ...