What is the reason for the improper setting of the div position?

Welcome to the interactive Pointer Pin application!

The red-bordered box is where you can drop your Pointer Pins. This area has a background image set.

The blue-bordered box is where you can drag various Pointer Pins from. These pins can be dropped into the red droppable region.

A black arrow represents a Dropped Pointer Pin.

Below is a snippet of the HTML code used:

<body>
<div id="Droppable" class="ui-ui-corner-all">
    Drop Area</div>
<div id="Draggable" class="ui-ui-corner-all">
    <img class="draggableItem" id="Item1" src="Images/pointer.png" alt="" />
    <div class="draggableItem" id="Item2">
        <img src="Images/pointer.png" alt="" />
    </div>
    ...
</div>

This application aims to achieve the following objectives:

1) Allows users to drop Pointer Pins onto the Droppable region.

2) Upon dropping a Pointer Pin, its Left Top position is captured using jQuery's position function and stored in a database via AJAX call.

3) The saved positions are retrieved and displayed on another page aligned with their original placement.

Issue Encountered:

Despite rendering the pointer positions where they were dropped initially, an offset discrepancy is present.

To address this issue, code samples have been provided that help understand how positioning data is managed in the application.

JavaScript Functionality:

    $(document).ready(function () {
        $(".draggableItem").draggable();

        $("#Droppable").droppable({
            drop: function (event, ui) {
                var droppablesPos = //Read dropped item postion using  jQuery .position()

              $.ajax({
                type: "POST",
                url: "/Feature/SavePointer",
                datatype: "json",
                traditional: true,
                data: { "Left": droppablesPos.Left, "Top": droppablesPos.Top},
                success: function (result) {
                    //return message to user
                },
                error: function (req, status, error) { }
            });
        });
    });

Please note, this code serves as a simplified overview to illustrate key functionalities.

For further insights, refer to the complete JavaScript and HTML snippets below:

 <script type="text/javascript">
...
</script>

<div id="Droppable" class="ui-ui-corner-all">
    Drop Area</div>
...
</div>

...

Answer №1

It is important to refrain from assuming the starting position of an element based on code that has not been executed. The correct way to retrieve the draggable position is within the drop event function:

 options.drop = function (event, ui) {
      // ui.offset left and top positions will give you the coordinates
      var leftPosition = ui.offset.left;
      var topPosition = ui.offset.top;
 }

I hope this explanation clarifies things for you :)

Answer №2

This code is quite unusual in its approach. Upon examining it, it seems that the draggable element was not actually physically moved to the droppable area. As a result, its DOM context remains within its original container, despite changes in x/y coordinates.

Therefore, extracting these coordinates will be relative to the original container rather than the droppable one. If you attempt to position the pointer within the droppable based on these coordinates, they will likely be incorrect.

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 Chart.js donut chart is not displaying as expected on the HTML page when using

My HTML code is set up to display a donut chart with database records retrieved through a PHP script. The data is successfully fetched and visible in the browser console, but the chart itself is not showing up. How can I resolve this issue? console.lo ...

Ways to gather all the elements on each page

Currently engrossed in a web scraping endeavor for a car website utilizing Selenium. One potential roadblock I've encountered is that the code seems to only iterate over the initial car element on the page, instead of going through the entirety of ava ...

When using HTML select tags, make sure to submit the actual text of the selected option instead of just the value attribute

There seems to be an issue with a form that I am submitting via POST where the option text is being sent instead of the option value. Here is my select declaration: <select name = "newfreq"> <option val='1'>every week</option ...

What are some ways to optimize and enhance the performance of my jQuery database ajax request?

As I delve into learning jQuery ajax and database queries, I have come across a specific scenario that I am seeking advice on. I currently have a simple form set up with an ajax function that checks a database for a certain code. Here is what I have so far ...

Trimming whitespace from strings within HTML tag attributes can be achieved using various methods

I have been reviewing the .cshtml pages of a website with the aim of adding ID attributes to various divisions and elements for testing purposes. These pages utilize AngularJS, and many of the elements I need to add ID attributes to are part of a list tha ...

Extracting data from XML using my custom script

I attempted to extract a specific value from an XML feed, but encountered some difficulties. In addition to the existing functionality that is working fine, I want to retrieve the value of "StartTime" as well. Here is the relevant section of the XML: < ...

Changing the appearance of a website by switching CSS stylesheets according to the size of the browser

Trying to build two versions of my website: one for mobile devices or small browsing windows, and another for large browser windows. Looking to link HTML to different style sheets based on browser size. Current attempt in code only addresses total screen ...

Modify jQuery to update the background image of a data attribute when hovering over it

Something seems to be off with this topic. I am attempting to hover over a link and change the background image of a div element. The goal is to always display a different picture based on what is set in the data-rhomboid-img attribute. <div id="img- ...

What is the best way to delete HTML classes that were generated by a function?

Currently, I'm immersed in the Etch A Sketch project as part of my journey through The Odin Project. Using DOM manipulation, I successfully created a grid and displayed it on the screen. Now, my aim is to allow users to resize the grid by removing the ...

Ways to transition to an iframe window

I am having difficulty selecting an iframe popup window as it is not coming into focus. Below is the image of the popup window along with the button I am attempting to click: https://i.stack.imgur.com/VzkOX.png This is the code snippet that I have been ...

Disable the jquery animation when the mouse leaves and return it to its initial state

My goal is to scale to 2.5 when hovering over the div element. The animation starts on hover, but if I quickly move my cursor out of the div, the entire scaling animation completes before returning to its original size. I want the animation to stop at its ...

Utilize a function to send an AJAX email

In my JavaScript function, I have been attempting to send an email from a contact form. The validation checks are working correctly, but when the code reaches the point of sending the form, it gets stuck and doesn't receive any response from $.ajax. I ...

Customize the style based on the state using styled components

I am currently working with a function component that looks like this: const Navbar = ({setNav, nav}) => { const [justify, setJustify] = useState('space-around') //get localStorage const user = JSON.parse(localStorage.getItem('user& ...

How can I create a single-page application that adjusts to different screen sizes effortlessly?

I am working on developing a single-page application that fits within one screen with the following structure: There is a fixed header that includes: Two columns (1/3 for left, 2/3 for right) : a logo on the left a breadcrumb on the right. The ...

How come my counter is still at 0 even though I incremented it within the loop?

Within my HTML file, the code snippet below is present: <div id="userCount" class="number count-to" data-from="0" data-to="" data-speed="1000" data-fresh-interval="20"></div> In my Ja ...

Preserve jQuery-enhanced webpage changes permanently

I am looking to permanently save modifications made on an HTML page using JQuery. I have come across suggestions about achieving this by sending an Ajax call and storing the data in a database table. However, I am unsure about what exactly needs to be save ...

Learn how to instruct ajax to fetch the designated information and retrieve corresponding data from the database based on the selected criteria

Looking for some help with my 2 select boxes. The first box allows users to choose a brand, while the second box should display products from that brand fetched from the database. Unfortunately, I'm not familiar with AJAX and the script provided by a ...

Effortlessly accessing API with AJAX login using jQuery

I'm trying to implement a login form using AJAX and jQuery for an API. When I run the following command in the terminal: $ curl -d '[email protected]&password=123123' The response includes a hash containing an API token and Auth I ...

Is there a way to retrieve a different value within the JavaScript code (imagepicker)?

I need help with setting up a page where users can choose an image to forward them to another page. However, I'm facing an issue when the user chooses two images at once. Can anyone provide ideas on how to handle forwarding in this scenario? You can c ...

Tips for dynamically populating JSON data using a dropdown selection?

I am currently exploring HTML forms as a new web developer. I have been experimenting with displaying JSON data in a div based on a selection from a dropdown menu using jQuery in Chrome. However, my code does not seem to be functioning properly. Even tho ...