Those skilled in the art of Drag and drop

Currently, I'm delving into the world of drag and drop functionality. While it's not overly difficult to grasp, there is one aspect that is really bothering me. As I navigate through this process, I stumbled upon this informative resource: http://www.w3schools.com/html/html5_draganddrop.asp

I'm puzzled as to why elements, such as images, stack on top of each other when dragged. Is there a method to prevent this stacking behavior? Ideally, I would like nothing to happen when a draggable element is dragged over another draggable element. Any assistance or guidance on how to achieve this would be greatly appreciated!

Answer №1

It seems like there might be some confusion, but I recommend learning from various sources of information to ensure you grasp all aspects of the lesson.

The original example included attributes in the div to enable content to be dragged and dropped onto it. Here is a snippet of the code with explanations for each attribute used.

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">


The key attributes are:

  • ondrop="drop(event), which triggers an event when the element is dropped
  • ondragover="allowDrop(event)", which allows the drop action to occur

The main takeaway here is that a div's ability to receive a 'drop' operation depends on having the necessary attributes set. If these conditions are not met (i.e.,

ondrop="drop(event)" ondragover="allowDrop(event)"
), the drop action will not be permitted.

I have retained and enhanced this example to provide a more comprehensive understanding since you are already familiar with it. Some points to consider include:

  • Notice how red highlighting persists if the draggable item is dropped on an invalid target. This demonstrates the completion of the 'drag' function, while the 'drop' function remains pending. The script modifies CSS properties to achieve these visual effects.
  • I have included multiple Codepen examples to showcase using different tabs/windows, contrasting with the W3Schools example to illustrate functionality without 'script' or 'style' tags.
  • The script is kept simple, setting CSS properties for each div individually and reusing variables intentionally for experimental purposes only.
  • In-code comments are provided to explain complex sections for easier comprehension.

http://codepen.io/anon/pen/WwdgbY
http://codepen.io/anon/pen/zqpJjo

Hopefully, this clarifies things for you!

Answer №2

Providing an overview of my creative vision:

I am looking to develop a dynamic list containing various elements that can be easily dragged and placed within a designated area. These elements should have the flexibility to move back and forth based on user preferences, while ensuring they do not overlap each other to avoid any content disappearing.

The next step involves creating a mechanism that identifies the selected elements within the drag area. Subsequently, I plan to utilize PHP to generate an email listing the chosen element names by the user - although this aspect is a completely separate endeavor!

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));
}
/*
if($("#div1").has(".drag-img").length)) {

}
*/
#element-box{
border-radius: 10px;
background-color: #333333;
height: 50px;
width:50px;
display: inline-block;
margin: 10px 20px;
}

#div1{
      width:400px;
      height:70px;
      padding:20px;
      border:1px solid #aaaaaa;
    }

    #drag1{
    background: red;
    }

    #drag2{
    background: blue;
    }

    #drag3{
    background: green;
    }

    #drag4{
    background: orange;
    }

    #drag5{
    background: hotpink;
    }
<div id="element-box" ondrop="drop(event)" ondragover="allowDrop(event)"><img class="drag-img" id="drag1" src="img/one.jpg" draggable="true"
ondragstart="drag(event)" width="100%" height="100%"/></div>
<div id="element-box" ondrop="drop(event)" ondragover="allowDrop(event)"><img class="drag-img" id="drag2" src="img/two.jpg" draggable="true"
ondragstart="drag(event)" width="100%" height="100%"/></div>
<div id="element-box" ondrop="drop(event)" ondragover="allowDrop(event)"><img class="drag-img" id="drag3" src="img/three.jpg" draggable="true"
ondragstart="drag(event)" width="100%" height="100%"/></div>
<div id="element-box" ondrop="drop(event)" ondragover="allowDrop(event)"><img class="drag-img" id="drag4" src="img/four.jpg" draggable="true"
ondragstart="drag(event)" width="100%" height="100%"/></div>
<div id="element-box" ondrop="drop(event)" ondragover="allowDrop(event)"><img class="drag-img" id="drag5" src="img/five.jpg" draggable="true"
ondragstart="drag(event)" width="100%" height="100%"/></div>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

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

How can I position a logo slightly off center to the left, rather than all the way to the left?

I attempted to implement this code: <div id="logo" style="background-image: url('http://comprogroup2ict2b.rf.gd/logo.png'); width: 100px; height: 50px; background-size: contain; background-repeat:no-repeat; float: left"> ...

Uncovering the origin of surprising reactivity issues in Vue 3 component workings

In my current project, I'm working on a basic Vue-3 app and encountering an issue that's puzzling me. The view in question is rendered through the router and consists of simple state components - an object reference for storing text field values ...

Transforming traditional HTML table layout to modern div structure

We are currently in the process of transitioning old pages from our previous website structure, which used tables, to our new layout based on DIVs. Our website is structured using a PHP include system with separate components for the header, body, and foot ...

Attempting to locate the element's position using Selenium in Python

quem_esta_sacando = driver.find_elements_by_xpath("//div[@class='gameinfo-container tennis-container']/div[@class='team-names']/div[@class='team-name']") this is how I located the correct class, but now I want to ...

Storing values in localStorage with a specific format can be accomplished by following these steps

How can I save a localStorage value with special characters? I currently have the following value: ald:20221219_1833|atrv:lMh2Xiq9xN0-is9qy6DHBSpBL3ylttQQew but when I try to store it, it appears as if there is an arrow indicating that the value can be ex ...

Tips for altering the appearance of a dropped item using JQueryUI sortable

I have a straightforward website where I need to implement the ability to drag and drop styled DIV elements between two containers. Utilizing JQueryUI's sortable function, this behavior was successfully achieved with the following code: $("#active-co ...

Definition list with alternating left and right alignments

Here is a definition list with a specific styling: dl { margin: 0; } dl.interview dt { color: #A8A67A; } dl.interview dd { margin-left: 0; } .interview dt:before { content: 'Q. '; } .interview dd:before { content: 'A. ...

Creating a dynamic table in VuetifyJS by populating it with data in real-time

Dealing with a dynamically changing table columns can be tricky. This means that hardcoding the template for the table like this example won't work: <template> <v-data-table :headers="headers" :items="items" hide-actions cl ...

HTML - implementing a login system without the use of PHP

While I am aware that the answer may lean towards being negative, I am currently in the process of developing a series of web pages for an IST assignment in Year 9. Unfortunately, the web page cannot be hosted and our assessor lacks the expertise to utiliz ...

Establishing communication between a master process and worker processes in Node.js: A guide to verifying bidirectional communication

After coming across this particular script from the node documentation, I tried to implement it for sending messages between Master and worker processes using cluster. However, upon running the script, I encountered an issue where I could not verify the me ...

Convert JSON objects within an array into HTML format

Is there a way to reformat an array of JSON objects that has the following structure? [{"amount":3,"name":"Coca-Cola"},{"amount":3,"name":"Rib Eye"}] The desired output in plain HTML text would be: 3 - Coca-Cola 3 - Rib Eye What is the best approach to ...

Is it possible to have both a Navbar and Sidebar concurrently using Bootstrap?

I have a slightly unconventional request - I want to incorporate the sidebar from along with the navbar-default example from http://getbootstrap.com/components/#nav. What would be the best approach to merge these two elements? Or is there a different pa ...

The functionality to apply a color class to a navbar item when clicked is malfunctioning

I'm attempting to create a navigation bar using text that toggles the visibility of different divs. I want the selected option to appear in red, indicating it has been chosen, while deselecting any other options. I am new to JavaScript and thought add ...

Utilizing BeautifulSoup for Web Scraping (handling missing values during the scrape)

I have been facing two challenges while trying to scrape data from a realtor website using BeautifulSoup. These issues have proven to be quite tricky: Challenges: After running my code snippet, I noticed that some date values are missing in the dataframe ...

What is the best way to iterate over a multidimensional array in Angular/Ionic?

I've been struggling to find a solution tailored for looping in a .ts file instead of HTML. My main objective is to iterate over an array and compare the entered value with the keys. If there's a match, I want to retrieve the values stored withi ...

Tips on modifying the width of grid lines for individual lines

Looking for assistance in adjusting the line width or color of a specific gridline on a Chartjs chart. In this scenario, I am aiming to enhance the grid-line width or alter the color of the horizontal gridline at y-axis 60 exclusively. Despite my efforts ...

The issue of AngularJS directives not populating correctly with their associated templates

I'm encountering some challenges with directives and their scope. I've developed a directive to fetch all the members of a site and display them within a div, here's the code snippet: EngagementApp.directive('siteMembers', [' ...

Confirming the manipulation of Node.js callbacks

I have been working on a scheduling program in Node.js to retrieve JSON data about courses. As I'm relatively new to Node.js, I'm looking for ways to improve my code and avoid callback hell. I have already implemented the getJSON method. /*getJS ...

Transmit data from list items in the HTML to a form

Based on my understanding, there are limited options available to style an <option> tag within a <select> dropdown and it appears quite plain. So I was thinking about creating a more visually appealing dropdown using <ul> <li> tags ...

Guide to Modifying the Parameter Value in JMeter's "Http Request" for a checkbox with "title" text managing the state

In the HTML code, there is a checkbox element that initially has the title "Select all rows in this table": <input type="checkbox" class="form-checkbox" title="Select all rows in this table"> Upon inspection, the title ...