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

Using React to Render a Component with Local Storage Information

I'm in the process of developing a history list component for a form within a react application and encountering difficulties with local storage. The goal is to display a list of previous user inputs from the local storage data. My current approach i ...

What is the method for calculating values entered into dynamic input fields?

I am facing a slight issue with my HTML form code... Within my code, there are several input fields that are being generated dynamically. Each dynamic input field contains a numerical value which I need to use for mathematical calculations. The calculati ...

Improve performance by debouncing computed properties and getters in Vue

I'm having trouble getting debounce to work with computed properties and Vuex getters. The debounced functions are always returning undefined. Check out this JSFiddle for an example HTML: <div id="app"> <input v-model="text"> <di ...

Activating a switch to execute a PHP code that displays a JavaScript code

At the conclusion of the button's click event, the following JavaScript code is executed: xmlObj.open ('GET', /ajax.php, true); xmlObj.send (''); } This will trigger the php script ajax.php located in the root directory: <?ph ...

OroCrm is ensuring that Symfony2 profiler seamlessly updates the footer data without triggering a 404 error page within a popup

As a newcomer to OroCrm, I recently installed and configured it on my DEV environment using the app_dev.php entry point. After setting up OroCrm, I immediately noticed the Symfony2 profiler bar appearing at the bottom of the interface. While this was a he ...

Styling with CSS to ensure divs are displayed in two rows

Check out this example I found: https://jsfiddle.net/n3qs0wke/ .wrapper { max-width: 600px; border: 1px solid #333; } .big-div { min-width: 212px; min-height: 212px; max-width: 212px; max-height: 212px; display: inline-flex; ...

Error in React Bootstrap: ReferenceError - 'openModal' is not defined

Whenever the button is clicked, my intention is for a modal to open. I have written the code for it, but I'm encountering errors that I can't seem to resolve. Here's the snippet of my code: import React from "react"; import { M ...

Enhance Summernote functionality by creating a custom button that can access and utilize

Using summernote in my Angular project, I am looking to create a custom button that can pass a list as a parameter. I want to have something like 'testBtn': this.customButton(context, listHit) in my custom button function, but I am unsure how to ...

Use PHP to open a text file and display its contents in a textarea

I have a textarea on my website and I'm trying to figure out how to populate it with the content of a text file. I followed a tutorial that guided me through writing some code, but when I implement it, I'm facing an issue where the words from the ...

Vue alert: Issue encountered in data() - "TypeError: Unable to convert undefined or null to object"

Can anyone help me figure out how to remove this warning? I suspect it's because I'm trying to manipulate an undefined object. Any assistance would be greatly appreciated! Thank you! Here is the code snippet: <v-card class="ma-3 pa-3" v-for=" ...

Press on any two table cells to select their content, highlight it, and save their values in variables

I have a table retrieved from a database that looks like this (the number of rows may vary): |Player 1|Player 2| ------------------- |Danny |Danny | |John |John | |Mary |Mary | My goal is to select one name from each Player column and sto ...

"Caution: Refs cannot be assigned to function components" message encountered when utilizing a custom component in Next.js

I created a component called HeaderIcon with the following code: function HeaderIcon({ inactiveIcon, activeIcon }) { const [isActive, setIsActive] = useState(false); return ( <div onClick={() => setIsActive(!isActive)}> {isActive ? ...

Panel div fails to show visNetwork visualization

After experimenting with shinyLP for creating html elements and crafting network diagrams using visNetwork, an interesting observation was made. When visNetwork is placed in a well panel or without any panel at all, it displays properly. However, the issue ...

Prevent event bubbling on a link generated by an Angular directive that includes transclusion

I am currently developing a directive that adds a link to a DIV element through transclusion. However, I am facing an issue where I want to execute specific functionality when the link is clicked without being redirected to the dummy href (in this case goo ...

Sort information based on the initial letter

My challenge is to accurately filter data by the starting letter only, not including middle letters. For example, if I have the word "Karnataka" and want to filter by the letter "K", searching with middle letters like "rna" still filters the result. Howe ...

Search through an array, identify duplicates, and transfer them into a separate array

I am working with an array of objects containing dates and I am looking to extract objects with the same date values into a new array. Below is the code snippet. var posts = [ { "userid": 1, "rating": 4, "mood": "happy", "date": "2 ...

Conceal the title attribute when hovering over a link using javascript/jquery

I have implemented the title attribute for all my links, but I want it to be hidden during mouse hover while still accessible to screen readers. var linkElements = document.getElementsByTagName('a'); for (var index = 0; index < linkElements. ...

Tips for updating the background color of a specific row

I have a piece of code that I am trying to modify with a specific condition. If {row.BB} is less than or equal to 100, I want to change the background color of the row with this value to red. Can someone help me achieve this? The code is linked to a data ...

What is the recommended alternative for the outdated or non-standard "align" element in use?

Here is the code I am working with in HTML: <td align="center"> After running ReSharper in Visual Studio 2008, I received this error message: "Element 'align' is obsolete or nonstandard" Can someone please advise on the correct replac ...

Revising the hierarchy between !important in CSS and jQuery

(Attempting to modify CSS properties within a Chrome extension content script) Is it feasible to override CSS properties that have been marked as !important on the webpage? For example, if I aim to eliminate an important border: $(".someclass").css(&apo ...