Shifting a div element around the webpage and letting it fall into place if it intersects with another div using plain JavaScript

Check out this jsFiddle link. Upon opening it, you will encounter a moveable div. However, I am looking to enhance this functionality by allowing the div to disappear if moved to the 'trash' area. Essentially, when you place the moveable div in the trash, it should vanish. Thank you for your assistance!

Here is my code snippet for moving the div:


var selected = null; // Object of the element being moved
var x_pos = 0;
var y_pos = 0; 
var x_elem = 0; 
var y_elem = 0; 

// Function to initialize dragging of an element
function _drag_init(elem) {
    selected = elem;
    x_elem = x_pos - selected.offsetLeft;
    y_elem = y_pos - selected.offsetTop;
}

// Function to move the element while dragging
function _move_elem(e) {
    x_pos = document.all ? window.event.clientX : e.pageX;
    y_pos = document.all ? window.event.clientY : e.pageY;
    if (selected !== null) {
        selected.style.left = (x_pos - x_elem) + 'px';
        selected.style.top = (y_pos - y_elem) + 'px';
    }
}

// Destroy the object after completion
function _destroy() {
    selected = null;
}

// Bind the functions...
document.getElementById('draggable-element').onmousedown = function () {
    _drag_init(this);
    return false;
};

document.onmousemove = _move_elem;
document.onmouseup = _destroy;

Answer №1

If more than 50% of the area is trash, discard the div

  1. Determine the x, y coordinates of both the trash and dragged elements
  2. Calculate the overlapping area between them
  3. If the overlap is greater than half of the div's area, hide it

Code

function getPosition(el) {
  var _x = 0;
  var _y = 0;
  while (el && !isNaN(el.offsetLeft) && !isNaN(el.offsetTop)) {
    _x += el.offsetLeft - el.scrollLeft;
    _y += el.offsetTop - el.scrollTop;
    el = el.offsetParent;
  }
  return {
    top: _y,
    left: _x
  };
}

function considerDiscarding() {
  var dragged = getPosition(document.getElementById('draggable-element'));
  var x11 = dragged.left;
  var x12 = dragged.left + 100;
  var y11 = dragged.top;
  var y12 = dragged.top + 100;
  var trashed = getPosition(document.getElementById('trash'));
  var x21 = trashed.left;
  var x22 = x21 + 100;
  var y21 = trashed.top;
  var y22 = y21 + 100;
  x_overlap = Math.max(0, Math.min(x12, x22) - Math.max(x11, x21));
  y_overlap = Math.max(0, Math.min(y12, y22) - Math.max(y11, y21));
  overlapArea = x_overlap * y_overlap;
  if (overlapArea > 100 * 50) {
    document.getElementById('draggable-element').style.display = 'none';
  }
}

See implementation here

References:

Retrieve coordinates

Calculate overlapped area

Answer №2

To find a solution that works, you can view my modified version of your jsFiddle

To address the issue at hand, I utilized the overlap function recommended in this particular answer, which makes use of Element.getBoundingClientRect()

function checkOverlap(element1, element2) {
    var rect1 = element1.getBoundingClientRect();
    var rect2 = element2.getBoundingClientRect();
    return !(rect1.right < rect2.left || 
                rect1.left > rect2.right || 
                rect1.bottom < rect2.top || 
                rect1.top > rect2.bottom)
}

// Clean up the object once we're finished
function _destroy() {
    // Check if an element is currently selected
    if (selected) {
        // Verify if the selected item overlaps with the trash element
        if (checkOverlap(selected, document.getElementById('trash'))) {
            // Remove the selected item from the DOM
            selected.parentElement.removeChild(selected);
        }
    }
    selected = null;
}

Answer №3

Below is a brief overview of the solution to your inquiry.

Link to Code Implementation

I have devised a function isInTrash(element) which assesses whether an element is in the trash and returns true if it is.

The criteria for verification includes determining if the mouse cursor, bearing the draggable element, rests inside the designated trash zone.

In addition, consider implementing some form of visual indication for the user when the element is being dragged over the trash area.

You can integrate the isInTrash function within your current function _move_elem(e) and adjust the color of the draggable element accordingly.

For further enhancement regarding feedback functionality, refer to:

Advanced Feedback Solution

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

The pair of divs with distinct backgrounds

Looking to customize the navigation on my website by creating a separate background for the list links menu and making sure the left part of the navigation with the logo has its own distinct background that extends until the next div. I've experimente ...

Issue with changing the height of a textarea in a mobile browser when it is

I'm currently facing an issue specific to mobile devices that I have also encountered on Google Chrome (even when using the developer tools in mobile view). The problem is quite straightforward. There is a simple form on the website, consisting of a ...

What is the best approach for accessing values from dynamic or multiple form fields upon submission in React?

In my form, users have the ability to add Textfields in order to include additional items. However, I am facing a challenge when it comes to retrieving these items from the form upon submission. The Textfields are dynamically created by a component functi ...

At what point are routed components initialized?

Here is a route setup I am working with: path: ':id', component: ViewBookPageComponent }, After adding this route, an error keeps popping up: Error: Cannot read property 'id' of null I haven't included a null check in the compo ...

The current page I'm working on is scrolling sideways, but I prefer a stationary layout without any scrolling

I am currently facing an issue with my webpage scrolling to the right. This behavior is not acceptable as web pages are not supposed to scroll to the right, correct? Could someone assist me in eliminating this unwanted scroll from my page? I have only u ...

specialized html elements within data-ng-options

I have a code snippet where I am populating select options from a controller using data-ng-options. However, I would also like to include an icon with each option. For example, I want to append <span class="fa fa-plus"></span> at the end of e ...

Alert: Route.get() is requesting a callback function, but is receiving an [object Undefined] while attempting multiple exports

I'm attempting to export the middleware function so that it can be called by other classes. I tried searching on Google, but couldn't find a solution that worked for my situation. Below is the code snippet: auth.js isLoggedIn = (req, res, nex ...

When working with Angular, the onSubmit method may sometimes encounter an error stating "get(...).value.split is not a function" specifically when dealing with Form

When the onSubmit method is called in edit, there is an error that says "get(...).value.split is not a function" in Form. // Code for Form's onSubmit() method onSubmitRecipe(f: FormGroup) { // Convert string of ingredients to string[] by ', ...

Is there a way to asynchronously load image src URLs in Vue.js?

Why is the image URL printing in console but not rendering to src attribute? Is there a way to achieve this using async and await in Vue.js? <div v-for="(data, key) in imgURL" :key="key"> <img :src= "fetchImage(data)" /> </div> The i ...

Display a webpage in thumbnail form when hovering the mouse over it

I'm in the process of creating a website that contains numerous sub-pages. I want to display all the links on a single page and when a user hovers over a link, I want to show a thumbnail of the corresponding webpage within a tooltip. I've experi ...

`A straightforward technique for establishing client-server communication using NodeJS`

Stumbling upon a valuable code snippet on GitHub for enabling straightforward server-client communication in NodeJS has been quite enlightening. Upon making some adjustments, the finalized structure of my code looks like this: The client (Jade + Javascri ...

Can native types in JavaScript have getters set on them?

I've been attempting to create a getter for a built-in String object in JavaScript but I can't seem to make it function properly. Is this actually doable? var text = "bar"; text.__defineGetter__("length", function() { return 3; }); (I need th ...

Exporting a VueJS webpage to save as an HTML file on your computer

Scenario: I am working on a project where I need to provide users with the option to download a static export of a webpage that includes VueJS as a JavaScript framework. I attempted to export using filesaver.js and blob with the mimetype text/html, making ...

Is there a way to detect if JavaScript is disabled using a unique CSS selector?

Does anyone know of a CSS selector that can be used when JavaScript is disabled? I'm not referring to the noscript tag, but specifically in CSS. ...

What are the steps for updating an NPM package that was installed from a Git repository?

I'm struggling to understand how to update a package that was installed from a git repository. Let's say I have a package located at git+ssh://<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d4b3bda094b3bda0b8b5b6fab1 ...

What is the reason for needing to export the function when importing a module in an Angular appModule?

I came across the following code snippet @NgModule({ declarations: [ ... ], imports: [ RoutingModule, SharedModule, JwtModule.forRoot({ config: { headerName: 'Authorization', tokenGetter: () => lo ...

Creating an indentation on one side of a div using CSS for a visually appealing effect

https://i.stack.imgur.com/io6m0.jpg I'm in the process of trying to create two shapes using CSS. I've been able to almost achieve the first shape on the left, but it extends out too far. As for the second shape, I'm having difficulties cre ...

PHP, jQuery, and MySQL combine to create a powerful autocomplete feature for your

I've implemented the source code from into my project, but I'm facing an issue where I can't retrieve any results when typing in the autocomplete textbox. Could someone point out where I might be making a mistake? This is the code I am us ...

Is it possible to execute a controller function only when the textarea has completely loaded?

My current setup includes a textarea as shown below: <textarea rows="3" maxlength="144" ng-maxlength="144" type="text" name="testPost" id="testPost_{{item.id}}" ng-init="focusText('testPost', item.id)" ng-model=" ...

Is it possible in Javascript to trace the origins of a particular element's property inheritance for debugging purposes?

I'm currently dealing with an issue where the computed style font-size of a particular element is "16px". I've been attempting to pinpoint where in the CSS or JavaScript this font size setting is coming from, specifically within one of its parent ...