Stop the click event from firing on child elements of a parent element that is currently being dragged

Below is the structure of a UL tag in my code:

<ul ondrop="drop(event)" ondragover="allowDrop(event)">
    <li class="item" draggable="true" ondragstart="dragStart(event)" ondrag="dragging(event)">
        <div class="product-infos">
            <a href="javascript:;"></a>
        </div>
    </li>
</ul>

I am looking to achieve the functionality where I can drag the entire LI element and drop it into another UL element using JavaScript.

<script>
    function allowDrop(event) {
        event.preventDefault();
    }
    function dragStart(event) {
        event.dataTransfer.setData("Text", event.target);
    }
    function dragging(event) {

    }
    function drop(event) {
        event.preventDefault();
        var data = event.dataTransfer.getData("Text");
        event.target.appendChild(document.getElementById(data));
    }
</script>

The issue I am facing is that when users click on different elements like "div" or "a", the drag operation fails as I end up appending the wrong child to the UL element. This results in the following error:

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

I want to enable dragging the entire element regardless of where the user clicks. Any suggestions for a solution would be greatly appreciated.

Answer №1

Utilize jquery ui sortable for a cleaner solution without the need for ondrag attributes in your HTML.

$(function() {
     $(function() {
         $( "ul" ).sortable({
            connectWith: "ul"
         });
         $( "ul").sortable({
            connectWith: "ul",
            dropOnEmpty: false
         });

      });
  });
ul{background-color:red;}
li{background-color:blue;}
a{background-color:green;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<ul ondrop="drop(event)" ondragover="allowDrop(event)">ul
    <li class="item">li
        <div class="product-infos">div
            <a href="javascript:;" draggable="true" ondragstart="dragStart(event)" ondrag="dragging(event)">link</a>
        </div>
    </li>
  <li class="item">li
        <div class="product-infos">div
            <a href="javascript:;" draggable="true" ondragstart="dragStart(event)" ondrag="dragging(event)">link</a>
        </div>
    </li>
</ul>
<ul ondrop="drop(event)" ondragover="allowDrop(event)">ul
    <li class="item">li
        <div class="product-infos">div
            <a href="javascript:;" draggable="true" ondragstart="dragStart(event)" ondrag="dragging(event)">link</a>
        </div>
    </li>
  <li class="item">li
        <div class="product-infos">div
            <a href="javascript:;" draggable="true" ondragstart="dragStart(event)" ondrag="dragging(event)">link</a>
        </div>
    </li>
</ul>

Answer №2

Switching from event.target to event.currentTarget could be the key in finding the solution you're looking for. Give it a try!

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

Utilizing Local Storage in Vuex Store with Vue.js

I have been working with localStorage for storing and retrieving items in my JavaScript code housed within a .vue file. However, I am now looking to find a way to transfer this stored data into my Vuex store, specifically within the mutations section locat ...

What's the best way to determine which of the two forms has been submitted in Django?

On my homepage, I have both a log_in and sign_up form. Initially, the log_in form is displayed by default, but when a user clicks on the Sign Up button, the sign_up form appears. These toggles switch depending on which button the user clicks. from django ...

Troubleshooting Issues with ASP.NET MVC5 CRUD Validation Inside Modal

My modal validation is functioning correctly, however, I am experiencing an issue where the form always returns valid()=false resulting in not hitting the Controller Method. I have attempted to use the unobtrusive.parse method for validation and it works ...

Error: Unable to execute function on blog mapping

I am facing an issue with my app where it fails to detect objects. Every time the component in my app calls ".map", I encounter an error message. I have double-checked that index.js is passing props correctly. Can anyone explain why this problem is occurri ...

The entire DOM has been seamlessly replaced by React.JS within the Node.js server

I am currently focusing on practicing the MERN structure, so my goal was to start by setting up a node.js server and react front-end. However, I encountered an issue where the entire DOM gets overwritten once the server is fired up. This has left me wonde ...

Tips for effectively utilizing MeteorPad: (Note: ensure to use at home instead of at work due to potential firewall or proxy issues)

UPDATE: It's possible that the issue is related to a firewall or proxy. MeteorPad doesn't work at my workplace, but it works fine at home. I've been attempting to use MeteorPad () but I'm encountering some difficulties. The bottom are ...

Eliminate the navigation bar background using MaterializeCSS

I want to create a unique extended navigation bar for my website that has the following structure: <nav class="nav-extended"> <div class="nav-wrapper"> <ul id="nav-mobile" class="right hide-on-med-and-down"> <li><a ...

Mock needed assistance

In my testing scenario, I am attempting to simulate a service that is utilized by my function using sinon. However, I am encountering difficulties in inserting the mock into my function. The service is obtained through the use of require The structure of ...

Calculating the total sum of values using a dropdown list as a filter with J

I have successfully implemented a dropdown filter in my jQuery datatable to filter data. However, I am now looking to calculate the sum of all values in the filtered table each time a user selects a value from the dropdown list. How can I achieve this? My ...

Leveraging Spotify's webAPI to listen to a randomly selected album by a specific artist (ID

Welcome to my little project! As I am not a developer myself, please bear with me for any silly questions that may arise. My idea is to create an "audio book machine." The concept involves using a website that showcases various artists of audiobooks. Upo ...

Could we confirm if this straightforward string is considered valid JSON data?

There are numerous intricate questions on Stack Overflow about whether a complex structure is considered valid JSON. However, what about something much simpler? "12345" Would the provided code snippet be considered valid JSON? ...

Enhancing Layouts with Bootstrap 5: Implementing Space Between Rows

Can anyone help me figure out how to add a vertical gutter between two rows with Bootstrap 5? I've tried using g-* and gy-*, but as shown in this jsfiddle, it doesn't seem to be working. Any ideas on what might be causing this issue? From my und ...

Is the "json_encode" function dropping the '+' character when using "json.parse"?

Seeking Assistance I have a question regarding the functionality of php function json_encode and js JSON.parse. I seem to be encountering an issue where the '+' character is being dropped somewhere in the process, particularly when dealing with ...

Prevent Duplicate Service Instances in Angular

After doing some thorough research online, I've identified the root of my issue: multiple instances of a particular service are being created. I need assistance in pinpointing and rectifying this problem within my code. The secondary service is depen ...

Grid of domes, fluid contained within fixed structures and beyond

I've been grappling with this issue for a while now, and have had to rely on jQuery workarounds. I'm curious if there is a way to achieve this using CSS or LESS (possibly with javascript mixins). The page in question consists of both fixed and f ...

How can you create a sophisticated JavaScript object with an intricate design?

In my code, I frequently instantiate an object with the following structure: costs: { totalPerYear, totalEver, perMonth: { items: { depreciation, insurance, credit, inspection, ...

Is there a better approach to verifying an error code in a `Response` body without relying on `clone()` in a Cloudflare proxy worker?

I am currently implementing a similar process in a Cloudflare worker const response = await fetch(...); const json = await response.clone().json<any>(); if (json.errorCode) { console.log(json.errorCode, json.message); return new Response('An ...

Send a bunch of checkbox values to the controller upon clicking in order to apply a filter to a query using

How can I filter the number of students by campus, year, and group using checkboxes? I have successfully filtered the result by Campus using this code, but the uncheck functionality is not working as expected. It still sends the checked value. I need to ...

Trigger a modal to open based on a specific condition

I have successfully implemented a default modal from Materialize, but now I am looking to add a conditional opening feature to it. In my application, there is a countdown timer and I want the modal to automatically appear when the countdown reaches a certa ...

Leveraging an external TypeScript library in a TypeScript internal module

Imagine you find yourself in a situation where you need to utilize a typescript/node library within an internal module that is spanned across multiple .ts files. ApiRepositoryHelper.ts import * as requestPromise from "request-promise"; module ApiHelp ...