Unable to move the image within the div container

I have a created a draggable div where I want to be able to drag and drop pictures into it. However, the main issue is that once the image is successfully dropped, it cannot be dragged within the div.

Code for working drag & drop:

$('div[role="textbox"]').on(
    'dragover',
    function (e) {
        e.preventDefault();
        e.stopPropagation();
    }
);
$('div[role="textbox"]').on(
    'dragenter',
    function (e) {
        e.preventDefault();
        e.stopPropagation();
    }
);

$('div[role="textbox"]').on(
    'drop',
    function (e) {
        // logic for handling image drop
    });

Code for drag & drop not working but dragging inside the div works:

// $('div[role="textbox"]').on(
//     'dragover',
//     function (e) {
//         e.preventDefault();
//         e.stopPropagation();
//     }
// );
// $('div[role="textbox"]').on(
//     'dragenter',
//     function (e) {
//         e.preventDefault();
//         e.stopPropagation();
//     }
// );

$('div[role="textbox"]').on(
    'drop',
    function (e) {
        //logic for handling image drop
    })

Is there a way to combine these two sets of code to make both functionalities work properly?

The image is simply inserted as an <img> element.

Answer №1

Here is a demonstration of the process you are looking to achieve:

<!DOCTYPE HTML>
    <html>
        <head>
            <script>
                function allowDrop(ev){ev.preventDefault()}

                function drag(ev){ev.dataTransfer.setData("text", ev.target.id)}

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

        <body>
            <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
            <img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">
        </body>
    </html>

Reference: http://www.w3schools.com/html/html5_draganddrop.asp

In my experience with cross-browser compatibility, if you need to drag and drop nested elements inside a div, it's important to cancel all drag events on the parent div.

element.ondragenter = function(event){event.preventDefault()};
element.ondragleave = function(event){event.preventDefault()};
element.ondragover = function(event){event.preventDefault()};

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

Play button icon is missing in Firefox when using absolute positioning

I'm currently experiencing an issue with my video gallery section. I have both normal and hover versions of a play button positioned above a preview image of a video. However, the play buttons are not visible at all in Firefox. You can view the page h ...

AngularJS offers a variety of 'select all' checkboxes tailored for specific lists of checkboxes

Within my webpage, I have three different sets of checkboxes. Each set includes a "select all" checkbox. Instead of repeating code lines, I am implementing a single function with a parameter to select specific checkboxes within each set. $scope.sele ...

Reveal a hidden div sliding in from the left within a parent div that contains multiple divs with the same class

I have come across a situation where I have multiple divs containing several hidden divs. The goal is to reveal each hidden div when hovering over a specific link. The problem I am facing is that the current code shows and hides all hidden divs at once. W ...

Style class for a division element

Feeling stumped. Here is the CSS code I am using: <style = "text/css"> .sidebar_qustions {padding: 10px; background-color: Green;} div.sidebar_qustions {padding: 10px;} DIV.sidebar_qustions {padding: 15px;} DIV .s ...

Using JavaScript to redirect input value for searching a particular webpage

Apologies for any confusion in my code, as I am still learning. I am looking to take an input value and redirect it to perform a search in another help system like Madcap. I have designed a bootstrap page with a search function in the hero banner, and I ...

RAZOR - Strip image elements from variable with HTML content

In the code snippet below, I am using a helper to display content: @Html.Raw(Model.PageData.PageContent) My goal is to filter out any image tags that may be present. I have explored methods like .substring(), but they require specific indices or string n ...

Utilizing jQuery's CSS function to adjust the "left" margin of multiple div elements

I am working on creating a menu bar that will be displayed at the top of my page. Each section of the menu will be a link to a different part of the page. $(document).ready(function() { var w = window.innerWidth || document.documentElement.clientWid ...

Dynamically scrolling an element using jQuery without specifying specific values

I need to keep an element fixed when scrolling on a page without setting specific height values. Do you know of any way to achieve this? Below is the code for reference: // Keep the orange box at the top after scrolling to a certain extent $(window).sc ...

Installation and execution of TypeScript jQuery / Bootstrap definition file on a local machine using npm typings: A step-by-step guide

Struggling to set up TypeScript jQuery and Bootstrap definition files in my new project using npm typings. Below are the steps I followed: 1- Open cmd, navigate to my project folder, and enter the following commands: npm install typings --global typings ...

Exploring the differences between Zurb Foundation 6's app.scss and _settings.scss files

Can you explain the distinction between app.scss and _settings.scss when using Zurb Foundation 6? ...

Ways to incorporate design elements for transitioning focus between different elements

When focusing on an element, I am using spatialNavigation with the following code: in index.html <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfb5acf2acafbeabb6beb3f2b1bea9b6 ...

The datepicker in jQuery disappears beneath the footer

While using the jQuery datepicker, I encountered an issue where it gets hidden behind the footer on the page. How can I resolve this problem? I have provided a link to my code on JSFiddle I have attempted to use the datepicker with a footer, but the ...

Issue with Angular 8: click event is not triggering when using ngFor directive to iterate through arrays of objects

Update: The original post has been modified to omit implementation details and complexity. I am facing an issue with an ngFor loop that invokes a method on a service. The method returns an array which is then iterated over by the for loop. The click even ...

Press the button to move to the following node

Is there a way to call a function on an image tag's click event without using a specific id, as the image tag has dynamic ids and I cannot directly use 'on-click'? I have tried the jQuery code below but it didn't work. Are there any oth ...

What is the best way to connect specific nodes to the edge of a canvas in cytoscape and create perfectly straight lines?

In the center column of my article, I have two graphs created with cytoscape showing "ancestors" and "descendants" on the sides. I am interested in displaying the connections ("edges") from the articles in the final generation of "ancestors" to the articl ...

Is it possible to eliminate auxiliary routes in Angular 4?

Recently, I came across an interesting scenario with two <router-outlet> tags, one with a name property. To test this, I set up the following router mapping: export const routing = [ {path:'', pathMatch:'full', component:E ...

Searching for hyperlinks with Datatables feature

In my current project, I have implemented a dataTable and everything is running smoothly except for one specific issue. During searches, the dataTable is also including text within href attributes of anchor tags, which is not desired in this case. http:/ ...

Verify if the ID exists in a different array using ES6

I needed to filter the data. My goal was to compare the data in data1 with the data in data2 and check for any error messages. Take a look at my code below. Is there a more efficient way to achieve this? data1 [ { "ids": "0111&q ...

What is the best way to create a board game layout inspired by Monopoly using HTML and CSS?

My goal is to create a square layout with smaller squares outlining it, similar to the tiles on a monopoly board. CSS isn't my forte, but I'm hoping to get the basic layout set up first and then play around to make it look nice. ...

Encountering an Uncaught TypeError when attempting to read properties of undefined, specifically 'backdrop', while incorporating a bootstrap 5 modal within a react environment

An issue occurred when attempting to display a Bootstrap 5 modal using JavaScript. const handleClick = (e) => { e.preventDefault(); const modalElement = document.getElementById('editUserModal'); const modal = Modal.getOrCreateInsta ...