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

Having difficulties executing AJAX requests on Codepen.io

My CodePen project that I created 6 months ago is no longer functioning properly. The project includes an Ajax call to retrieve data using jQuery.ajax(). When attempting to load the content from CodePen via https, even though the ajax request is through h ...

How can I align the isometric camera in THREE.js to the center of a cube?

Hey there, I'm working on a tricky exercise involving setting up a camera and cube with THREE.js. The goal is to maintain the cube's initial ratio while ensuring the camera is focused on the center of the cube. Although I believe I've succes ...

Addressing the issue with this.setState and this.state on the Registration page

I am facing an issue with my Registration Page code. I am trying to send data to a database using this.setState and this.state, but every time I run the code, it shows an error in the onSubmit function related to this.state. Can someone please help me unde ...

Enhancing User Experience with CSS Transitions for Faster Page Loading

Recently, I stumbled upon a captivating website that has left me in awe - . The mesmerizing aspect of this site lies in the seamless and fluid animations that gracefully transition when navigating between pages. I find myself yearning to understand the int ...

Adjust the primary scrolling section of a webpage to halt once it reaches a specific distance from the bottom of the viewport

I am facing a situation where I need to ensure that when scrolling down, a fixed pink menu bar at the bottom of the page does not overlap with the main blue content. This can be achieved by treating the blue content as an iframe positioned 60px from the bo ...

How can I dynamically insert a new HTML element into $event.target using Angular 2?

I have a webpage with a list of items. I want to display a "copy" button next to each item when the mouse hovers over it. I am currently able to create the "copy" button within the element using the following method: mouseOver(event) { if (event.tar ...

The dropdown feature in Bootstrap 4 only works once in a Rails application

After updating to Bootstrap 4.0.0, setting it up in Rails 5.1.5 based on the README from their github, and adding it to the package.json for yarn, I encountered an issue. Here is the setup in gemfile : gem 'bootstrap', '~> 4.0' gem ...

Ways to enhance a Vue component using slots

I am looking to enhance a third-party library component by adding an extra element and using it in the same way as before. For example: <third-party foo="bar" john="doe" propsFromOriginalLibrary="prop"> <template v ...

Display intricate header and preview in a printed datatable

Hey there, I've been using the Datatable plugin and it's really great. However, I've come across a problem with complex headers like this: <thead> <tr><td>some text</td></tr> <tr><td>some te ...

Designing a straightforward thumbs-up icon

Hey there! I'm currently working on a blog application and trying to set up a simple like button for each post identified by its primary key (pk). However, I encountered an error along the way. The error message I received is "NoReverseMatch at /sing ...

The containerElement is not compatible for routing when using a menuItem in React JS

Greetings, I am fairly new to working with React.js and I am currently exploring how to implement routing using material-ui MenuItem. However, I seem to be encountering some difficulties when trying to utilize the ContainerElement feature upon clicking on ...

The route is redirecting to an incorrect destination

Whenever a button is clicked on my webpage, this particular function is triggered. $scope.go=function(takenAt){ var path = '/oneMinuteMetric/loadCapturedMetrics?'+'&timestamp=' + takenAt + '&tagName='+ $stateParam ...

Best approach for retrieving and adding a large number of images when dealing with slower connections

Currently, I am retrieving 100-200 images using a combination of ajax-php-mongodb. The process involves ajax making an initial call with parameters, php on the server side locating the appropriate mongo document containing all image file ids in grid fs, fe ...

What is the best method to access an element with Vue.js?

I currently have a form set up like this <form v-on:submit.prevent="save_data(this)"></form> and a method defined in Vue.js like this methods: { save_data: function(f){ } } In jQuery, we can access the form using $(f)[0] My question ...

"Redirecting visitors based on their location using GeoIP targeting for

Is there a way to implement a code that redirects users based on their location? For example, if a user accesses the site from the United Kingdom, they should be redirected to /UK/, if from the US to /US/, and if from anywhere in the EU (excluding the UK) ...

Choosing2 ajax managing outputs

Using select2 with ajax search queries to the database is going smoothly, but there is a small issue that I am encountering. For instance, when searching through IDs in the database and start typing '111' into select2, it shows 2 rows with the I ...

Stop jQuery function from activating twice during scrolling

I'm looking for a solution to optimize my code that detects if an element is in the viewport and triggers certain actions. Currently, it re-runs the code every time a scroll event occurs when the element is above the fold. Is there a way to make it on ...

Experience a login page similar to Google's with a fully functional back button

I'm currently working on a login page that requires the user to enter their username and have it validated before proceeding. Once the username is confirmed as valid, a new input field for password entry should appear. However, I'm facing an issu ...

What is preventing my application (docker) from connecting to the database?

Encountering a frustrating issue here: I've developed a NodeJS application with a server listening on port number 3000. The app includes simple operations such as post, put, and read, which interact with a database running in a Docker Container on por ...

How do I apply a xPage page style using the styleClass attribute instead of directly using the style attribute

Would like to know how to change the background color of an entire page using styleClass instead of directly in the xp:view tag? Here's an example that works: <xp:view xmlns:xp="http://www.ibm.com/xsp/core" style="background-color:#f1f1f1;"> ...