JS - Activate the ghost element feature by using the preventDefault function

I am currently working on a project where I need to drag elements from a list of img tags to various svg:rect containers.

The process involves using mousedown and mouseup events to track which img is being picked from the list and where it is dropped within the svg:rect containers.

Below is the code snippet:

<body>

<div style="border: 1px solid black">
    <svg width="300" height="100">
        <rect id="container" width="60" height="60"></rect>
        <rect id="container2" x="70" width="60" height="60"  fill="salmon"></rect>
    </svg>
</div>

<div id="list">
    <img id="item" src="img/cat.png" width="64" />
</div>

<script>

    const container = document.getElementById('container');
    const container2 = document.getElementById('container2');
    const item = document.getElementById('item');

    let drag = null

    item.addEventListener('mousedown', function (e) {
        e.preventDefault();
        console.log('mouse down from IMG');
        drag = e.target;
    });

    container.addEventListener('mouseup', function (e) {
        e.preventDefault();
        console.log('Container 1', drag);
        drag = null;
    });

    container2.addEventListener('mouseup', function (e) {
        e.preventDefault();
        console.log('Container 2', drag);
        drag = null;
    });
</script>

My issue lies in the fact that by using e.preventDefault() in the img event listener, the ghost element effect is lost when dragging the image. Is there a way to maintain this effect while still utilizing the preventDefault() call?

Answer №1

The mysterious occurrence of the ghost element is due to the inherent draggable property of the <img> tag

To achieve the desired effect, one can utilize the ondragstart event on the image and pair it with the ondrop event on another element. You can refer to this example for guidance.

Regrettably, this method does not work with rect elements. One alternative solution could involve utilizing the onmouseover event on the rect elements, although the user would need to move the mouse after dropping for it to function correctly.

const container = document.getElementById('container');
const container2 = document.getElementById('container2');
const item = document.getElementById('item');

    let drag = null

function dragImg (e) {
        //e.preventDefault();
        console.log('ondrag IMG');
        drag = e.target;
    };

// Not working
function ondrop1 (e) {
        //e.preventDefault();
        console.log('Container 1', drag);
        drag = null;
    };

// Not working
function ondrop2 (e) {
        //e.preventDefault();
        console.log('Container 2', drag);
        drag = null;
    };
<div style="border: 1px solid black">
    <svg width="300" height="100">
        <rect id="container" onmouseover="ondrop1(event)" width="60" height="60"></rect>
        <rect id="container2" onmouseover="ondrop2(event)" x="70" width="60" height="60"  fill="salmon"></rect>
    </svg>
</div>

<div id="list">
    <img ondragstart="dragImg(event)" id="item" src="https://ddragon.leagueoflegends.com/cdn/8.22.1/img/champion/Velkoz.png" width="64" />
</div>

[EDIT] For a more seamless experience using rect elements, consider incorporating the ondrop event on the svg, then locate the rect element under event.target. Refer to documentation here for further details.

Best of luck!

Answer №2

Through thorough research and experimentation, I have identified two potential solutions:

Initial approach: Avoid using HTML5 drag and drop altogether.

Instead, utilize the mousedown event on the draggable element and mouseup event on the droppable element. Within the mousedown event, be sure to include a preventDefault() call to eliminate the ghost element effect during dragging. To recreate this effect, construct your own ghost element with CSS properties such as pointer-events: none and position: absolute.

Alternative solution: Employ the HTML5 drag and drop feature partially.

Add a dragstart event to the draggable element (image) and drop and dragover events to the droppable element (SVG). Within the drop event, check for e.target to obtain a reference to the svg:rect element.

An example can be found here: https://gist.github.com/EduBic/49e36485c70c5a6d15df7db1861333de

Note: Be sure to incorporate additional events and handle various scenarios accordingly.

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

Transforming PHP shortcode into JQuery functionality

My website is built on Wordpress, and I use javascript to load some of the content. Here's an example: jQuery(".portfolio-fs-slides").css({"display":"none"}).prepend('<div class="portfolio-fs-slide current-slide portfolio-ppreview"><d ...

Using jQuery with an SVG map may result in issues with the URL hash not updating correctly

In my current project, I am developing a locator app using an SVG map and jQuery functionality. The idea is that when a user clicks on a state within the map, it should display campuses located within that specific state by pulling data from a JSON feed. T ...

Unable to manipulate the marker with the leaflet library

Currently, I am utilizing react.js with the leaflet library and would like to enable marker movement on the map when clicked, instead of adding a new one. Below is the code snippet I am working with: import React from "react"; import { MapConta ...

What is the solution to the error message stating that <tr> cannot be a child of <div>?

displayTodos() { return this.state.todos.map(function(item, index){ return <div todo={item} key = {index}>; <tr> <td>{item.todo_description}</td> <td>{item.todo_responsible}</td> ...

Fixing a CSS animation glitch when using JavaScript

I'm facing an unusual issue with my CSS/HTML Check out my code below: a:hover { color: deeppink; transition: all 0.2s ease-out } .logo { height: 300px; margin-top: -100px; transition: all 0.2s ease-in; transform: scale(1) } .logo:hover { transit ...

AngularJS application is throwing an error indicating provider $q is not recognized

Could someone please advise on what might be the issue with my code snippet below: var app = angular.module('app', [ 'angular-cache', 'angular-loading-bar', 'ngAnimate', 'ngCookies', &a ...

Utilizing JavaScript for enhancing the appearance of code within a pre element

Is there a way to dynamically highlight the code inside a pre element using vanilla JavaScript instead of JQuery? I'm looking for a solution that colors each tag-open and tag-close differently, displays tag values in another color, and attributes with ...

Having trouble with spawning child processes asynchronously in JavaScript

I'm trying to figure out how to format this code so that when a user clicks a button, new input fields and redirect buttons are asynchronously inserted into the unordered list. Everything was working fine until I added the redirect button insertion fu ...

Searching for different forms of multiple words using regular expressions

I have a value saved in a variable: var myvalue = "hello bye"; var myText = "hellobye is here and hello-bye here and hello.bye" Is there a way to check if different versions of myvalue are present in the text? I am currently using this pattern: hello ...

calculation of progress bar advancement

I want to make the progress bar in my game responsive to changes in the winning score. Currently, it moves from 0% to 100%, which is equivalent to 100 points - the default winning score. But I need the progress bar to adjust accordingly based on the user-i ...

NuxtJs: Oops! It looks like NuxtError is not defined in this context

Exploring NuxtJs is new to me. I decided to experiment with how nuxt-link functions by purposely setting up a nuxt-link to a non-existent route in order to trigger the default 404 page. Here's the line of code I added to the pages/index.vue file: < ...

The cookies() function in NextJS triggers a page refresh, while trpc consistently fetches the entire route

Is it expected for a cookies().set() function call to trigger a full page refresh in the new Next 14 version? I have a chart component that fetches new data at every interval change, which was working fine when fetching the data server-side. However, since ...

hierarchical browsing system

Take a look at the image provided below. Currently, I am using multiple unordered lists - specifically 5. However, I would prefer to consolidate them all into a single nested ul. I am encountering two issues: How can I add a border-bottom to the hori ...

Locate the next element with the same class using jQuery across the entire document

I'm working with the following HTML: <section class="slide current"></section> <section> <div class="slide"></div> <div class="slide"></div> </section> <section class="slide"></section> ...

My code to hide the popup when clicking outside doesn't seem to be working. Can you help me figure out why?

After searching around on stackoverflow, I stumbled upon a solution that worked for me: jQuery(document).mouseup(function (e){ var container = jQuery(".quick-info"); if (container.has(e.target).length === 0) { container.hide(); } }); ...

Javascript promise failing to deliver

As a beginner in the world of JavaScript development, I am excited to be part of the stackoverflow community and have already gained valuable insights from reading various posts. Currently, I am facing an issue where I need to load a file, but due to its ...

Refreshing Form in Angular 2

When I remove a form control from my form, it causes the form to always be invalid. However, if I delete a character from another input field and then add the same character back in (to trigger a change event), the form becomes valid as expected. Is ther ...

Connecting multiple promises using an array

After making an ajax call to retrieve an array of results, I have been attempting to process this data further by making additional ajax calls. However, when using Promise.all() and then continuing with .then(function(moreData){}), I noticed that the moreD ...

Issue with Jquery focus on dropdown not working

I am facing an issue with setting up the dropdown feature for my list. It's similar to ul li:hover ul li. What I'm trying to achieve is something like ul li:focus ul li in jQuery because I don't think it can be done using CSS. The desired ou ...

What is the method for retrieving the IDs of checkboxes that have been selected?

I attempted running the following code snippet: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://static.jstree.com/v.1. ...