What is the process for calculating and determining the exact area the div should be released?

I am currently developing a drag-and-drop application using only Javascript. I have successfully implemented the dragging functionality, allowing elements to be moved randomly within the page. However, I now face the challenge of creating a drop zone with 9 boxes (divs) that need to receive these dragged elements. I am seeking a suitable approach to achieve this task efficiently. My initial thought is to set these divs as 'absolute' and reposition them using the top and left attributes. But how should I proceed from here? How can the dragged div, activated onmousedown, detect where it should drop when released onmouseup? For instance, if I select div number 1, it should be dropped into target number 1.

Below is the snippet of Javascript code I am currently employing for selecting and dragging:

window.onload = function() {
    var el = document.getElementById('block1');
    var mover = false, x, y, posx, posy, first = true;
    el.onmousedown = function() {
        mover = true;
    };
    el.onmouseup = function() {
        mover = false;
        first = true;
    };
    el.onmousemove = function(e) {
        if (mover) {
            if (first) {
                x = e.offsetX;
                y = e.offsetY;
                first = false;
            }
            posx = e.pageX - x;
            posy = e.pageY - y;
            this.style.left = posx + 'px';
            this.style.top = posy + 'px';
        }
    };
};

Answer №1

My approach would be to implement functionality that detects when the mouse enters a target area ("onmouseenter") and sets a Boolean value to true for that specific target. This Boolean value would then be set to false when the mouse leaves the target area ("onmouseleave"). Upon triggering an "onmouseup" event, the code would check all the Booleans to determine if div1 has been dropped and if target1 is true, then move div1 to the position of target1.

While this explanation may seem like pseudo code, it provides insight into my thought process for solving the issue at hand.

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

Compiling 'react-scripts' to include a few images as data URIs within the CSS file

I have recently inherited a sizable React project, even though my experience with React is limited. Nonetheless, I am attempting to make improvements in areas where I feel confident. An ongoing issue we are facing is the excessive size of our main CSS fil ...

What could be causing the shake effect on the MUI dialog to not work when clicking away?

I am trying to implement a shake effect when the user clicks outside the MUI dialog to indicate that clicking away is not allowed. However, the code I have so far does not seem to be working as the effect is not being applied. Can someone please help me ...

Updating the @mui/x-data-grid table dynamically upon fetching new data

Seeking assistance regarding updating data in the DataGrid component from the @mui/x-data-grid module within a React application. Specifically, I am facing challenges in refreshing the table after retrieving data from an API using react-query. Despite succ ...

Center aligning elements in React using CSS with HTML can be achieved through Flexbox. However, sometimes images

Currently, I'm in the process of developing a website with react and I've encountered an issue with centering elements vertically on the left and right sides. It's been troubling me for a few days now and I haven't found a solution yet. ...

The initial drag function seems to be dysfunctional in vue-smooth-dnd for vuejs

Check out the code snippet below for a drag and drop section. The div with the class drag-block should be draggable, but it doesn't work on the first attempt; it only drops when we drag it for the second time. https://github.com/kutlugsahin/vue-smoot ...

Alternating row colors using CSS zebra striping after parsing XML with jQuery

After successfully parsing XML data into a table, I encountered an issue with applying zebra stripe styling to the additional rows created through jQuery. Despite my efforts to troubleshoot the problem in my code, I remain perplexed. Below is a snippet of ...

angucomplete-alto automatically fills in data based on another input

Having two autocomplete select boxes with a unique feature has been quite interesting. The first input accepts a code that is related to a label, autofilling the second input with the corresponding object once the code is selected in the first input. Howev ...

Data structure for Highcharts:

Recently, I've been experimenting with Highcharts (http://www.highcharts.com) in a test application built on rails 3.1.1 and HAML. As someone who is still new to JavaScript, I'm striving towards achieving a seamless integration of Highcharts. Wi ...

Cloning a file input does not retain the uploaded file in the cloned input. Only the original input retains the uploaded file

Whenever I duplicate an input type file, I encounter an issue where the uploaded file from the duplicated input is also linked to the original input. It seems like the duplicate input is somehow connected to and taking files for the original one. This is ...

The epoch time indicates a 12-hour difference

I keep encountering an error with the time showing as 12:00 P.M. When I receive a response in epoch time format 1454092200000, it corresponds to 1/30/2016, 12:00:00 AM GMT+5:30 $scope.shipmentDate = moment(1454092200000).format("YYYY/MM/DD hh:mm"); The ...

Help with enabling the recognition of backspace key in JavaScript?

My current JavaScript is almost perfect but missing one key element. The form has two fields that are disabled when the user fills it out. <label>Can you drive? </label> <input type="booleam" id="drive" disabled><br> <label>W ...

Is it possible to incorporate a next.js image onto the background design?

I've encountered an issue while attempting to create a fixed background image with a parallax effect using Tailwind CSS and Next.js Image. If you need to see an example of this in action, check out this Template Monster theme. Here's the code s ...

Is it possible to use multiple schemas for one collection name?

I am currently working on creating different schemas for a single collection, such as User or subUser. I aim to store both User and subuser data in the same collection but with different schemas. Here is an example of my schema file: export const AryaSchem ...

When using React.js, clicking on an answer option will change the color of all options, not just the one that was clicked

I'm currently working on my quiz page where all answer options change color when clicked. However, I only want the selected answer option to be colored based on its correctness. The data is being retrieved from a data.json array. export default functi ...

"Retrieve real-time information from the server directly on the client side

Within my express router, I validate the data submitted on a form and then render another page if the data is valid, passing along the form data. My goal is to be able to access this passed data on the client-side. In the chat.ejs view, I have a chatroom.j ...

flexbox wrapping text styling

Can text be wrapped in flex within a fixed width container? For example: img username added you as a friend Instead of: user added img name you as a friend I am able to achieve this if the image and 'a' were separat ...

jQuery Animation Issue: SlideDown Effect Not Working as Expected

I'm feeling quite confused about this situation. I've been attempting to utilize the slideDown function in jQuery, but when I click on the 'information' div, it just jumps instead of animating smoothly. I suspect that one of the cause ...

Tips for sending parameters to XSLT using a Javascript function

Despite my efforts to find a solution in various online posts, I haven't been able to resolve the issue. The challenge lies in my HTML file that includes a JavaScript function for parsing XML and rendering XSLT. I have multiple 'records' in ...

The callback function in jQuery does not function properly in a custom class or object

Hello, I am new to the world of programming so bear with me if this question seems basic. I am currently working on creating a simple wave effect to give the illusion of moving water. Initially, I achieved this using a straightforward jQuery function which ...

When deploying a website with the default Hugo theme on Netlify, I encountered a strange issue where the webpage appeared blank. Sur

After coming across a question similar to mine about creating a static page using blogdown with the same Hugo theme as the main site on Stack Overflow, I still find myself struggling to understand the solution provided. As an absolute beginner, I am curren ...