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

Using jQuery to clear a textarea when a select input is changed

Currently, I am in the process of developing a small text editor that enables users to edit files and create new ones. Here is how I have set up my select menu. <select name="reportname" id="reportname" class="form-control"> <option value="zr ...

JavaScript Canvas - Preserve Image Transparency

I have been trying to download a snapshot of a canvas using the code below: var strMime = "image/png"; var canvas = document.getElementsByTagName('canvas')[0]; var link = document.createElement("a"); link.href = canvas.toDataURL( ...

Obtain the URL path for accessing URL links using PHP

To obtain the URL of an image, I typically use this code on the main websites: <a href="./index.html"><img src="./images/logo.png" class="" alt=""></a> However, for sub-sites, I need to use a slightly different approach: <a href=".. ...

Is there a way to ensure that the 'pointermove' event continues to trigger even after the dialog element has been closed?

I am working on a project that involves allowing users to drag elements from a modal dialog and drop them onto the page. I have implemented a feature where dialog.close() is called once the user starts dragging. This functionality works perfectly on deskto ...

Encountering issues with Html.ActionLink in Asp.net MVC when using Bootstrap Select

I am trying to implement a dropdown list for language localization on my website. However, when using <ul> tags with Html.ActionLink, the links are created with language codes as shown below: @{ var routeValues = this.ViewContext.RouteData.Valu ...

I seem to be experiencing difficulty receiving the JavaScript alert on my controller page

In my ActionResult function, I have the following code: public ActionResult Copy( int bvVariableid ) { var iReturn = _bvRepository.CopyBenefitVariable( bvVariableid, CurrentHealthPlanId, CurrentControlPlanId, _bvRepository.GetSecInfo( ).UserId ...

Utilize jQuery to invoke an ASP page method from an HTML page

I have a static web page named index.html which includes text boxes for data input. My goal is to send this data to an ASP page called Default.aspx using jQuery/AJAX. I attempted the following: $.ajax({ url: "Default.aspx/GetData", ...

Can a jumbotron and navigation bar be permanently attached to the top of a screen?

Currently, I am in the process of constructing my website using Bootstrap and my goal is to ensure that the header and navigation bar remain fixed at the top of the page while the content below scrolls underneath. While I am aware that it is possible to fi ...

Using ng-if in AngularJS to compare two objects

I am transferring between controllers with different formations, and I am attempting to use "ng if" to compare the ids, but it is not functioning as expected. Below is the code snippet: var postsApi = 'http://mywebsite.com/wp-json/posts?filter[p ...

Design a styled rectangular tab using CSS

Does anyone know of any cool CSS techniques for achieving the tabbed rectangle appearance depicted in the image below? While it's clear that accomplishing this with just one div is not possible, is there a more efficient method than layering one div ...

Is it possible that CSS files are not being excluded from content scripts in manifest.json?

I am looking to create a chrome extension that enforces a specific CSS style on all websites except for Gmail. However, I am facing an issue where the code in the content scripts section of the manifest.json file is not working as expected. Even though I h ...

What is preventing me from translating JS Canvas Image?

I've been struggling with using ctx.translate() to translate images on a canvas. No matter what I do, it just won't work. I've spent a good amount of time trying to troubleshoot the issue. Here's the snippet of code I'm working wit ...

Tips for positioning the navbar to avoid covering the logo:

I am experiencing difficulty in aligning my navbar. When I resize the window, the navbar overlaps with the logo... Here is the Fiddle Here is the code: <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation" style="background: rgba(0,0, ...

Looking to execute a PHP script upon form submission

I have a form that I need to submit in order for a PHP script to run using AJAX. <form method="post" action="index.php" id="entryform" name="entryform"> <input type="submit" name="submit" value="Submit" onclick="JavaScript:xmlhttpPost('/web/ ...

Tips for resolving flickering animations in CSS and JavaScript

Is it possible to dynamically set a scale and margin for an element in order to center it fluidly using the wheel event? I am aiming to achieve a smooth transition while also adjusting scroll position on the wrapping element in a fluid manner. In the prov ...

Guide to retrieving a file stored locally with VueJS

Currently, I am working on an upload system and I want to provide users with a sample template. The template is stored locally in a subfolder within the assets directory. My goal is to access this template in my VueJS component and display a link to it on ...

The onpopstate event listener is specifically targeting a single page range

I have implemented a function that pulls dynamic content from a database, triggered by specific link clicks: Utilizing jQuery <script> function loadContent(href){ $.getJSON("/route", {cid: href, format: 'json'}, function(results){ $("#c ...

"Effortlessly create a disappearing effect for your Bootstrap modal: Fade in upon opening, and instantly

When it comes to Bootstrap 3 modals, I have a question regarding the fade effect. On my outer modal div, I am using class="modal fade" to achieve the default fade in/out effect. However, what I really want is for the modal to fade in when opened, but disap ...

What approach do you recommend for creating unique CSS or SCSS styles for the same component?

Consider a scenario where you have a complicated component like a dropdown menu and you want to apply custom styles to it when using it in different contexts. This customization includes not only changing colors but also adjusting spacing and adding icons. ...

Styling Labels with CSS Wildcard

I have been using the free NinjaForms plugin on my WordPress site. The default styling for labels is bold, but I prefer them to be lighter. Currently, I achieve this through CSS by targeting individual field IDs. However, this method becomes tedious when a ...