Tips for tackling drag and drop functionality with only HTML, CSS, and JavaScript

Currently, I am faced with a challenge involving drag and drop TEST.

Observing the image provided below, you will notice 3 columns each containing 3 small boxes of varying colors. These boxes are draggable, meaning they can be moved between columns following two specific conditions:
● Two identical colored boxes cannot exist in the same column. For example, both the first and second columns have green boxes, so the green box from the first column cannot be dropped into the second column but can be placed in the third column.
● Drag and drop actions should only occur within the column area. If a box is dragged and dropped outside of a column, it should return to its original position

Presented here is the code which unfortunately does not successfully identify matching colors...

var p = document.getElementsByTagName('p');
var choice = document.getElementsByClassName('choice');
var dragItem = null;

console.log(p)

for (var i of p) {
  i.addEventListener('dragstart', dragStart);
  i.addEventListener('dragend', dragEnd);
  console.log(i)
}

function dragStart() {
  dragItem = this;
  setTimeout(() => this.style.display = "none", 0);
}

function dragEnd() {
  setTimeout(() => this.style.display = "block", 0);
  dragItem = null;
}

for (j of choice) {
  j.addEventListener('dragover', dragOver);
  j.addEventListener('dragenter', dragEnter);
  j.addEventListener('dragleave', dragLeave);
  j.addEventListener('drop', Drop);
}





function Drop() {
  this.append(dragItem)
}

function dragOver(e) {
  e.preventDefault()
}

function dragEnter(e) {
  e.preventDefault()
}

function dragLeave() {}
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="./style.css">
  <title>drag & drop</title>
</head>

<body>

  <h1>Rank in order as your choice</h1>
  <section>
    <div class="choice">
      <p id="green" draggable="true">Green</p>
      <p id="orange" draggable="true">Orange</p>
      <p id="purple" draggable="true">Purple</p>
    </div>
    <div class="choice">
      <p id="yellow" draggable="true">Yellow</p>
      <p id="green" draggable="true">Green</p>
      <p id="orange" draggable="true">Orange</p>
    </div>
    <div class="choice">
      <p id="pink" draggable="true">Pink</p>
      <p id="skyblue" draggable="true">Skyblue</p>
      <p id="purple" draggable="true">Purple</p>
    </div>


  </section>

  <script src="./index.js"></script>
</body>

</html>

Answer №1

Check if the target element contains the ID of the dragged element upon drop

function Drop() {
  if (this.querySelector('#' + dragItem.id)) {
    return;
  }
  this.append(dragItem)
}

Snippet

var p = document.getElementsByTagName('p');
var choice = document.getElementsByClassName('choice');
var dragItem = null;

//console.log(p)

for (var i of p) {
  i.addEventListener('dragstart', dragStart);
  i.addEventListener('dragend', dragEnd);
  i.style.background = i.id;
  //console.log(i)
}

function dragStart() {
  dragItem = this;
  setTimeout(() => this.style.display = "none", 0);
}

function dragEnd(ev) {
  setTimeout(() => this.style.display = "block", 0);
  dragItem = null;
}

for (var j of choice) {
  j.addEventListener('dragover', dragOver);
  j.addEventListener('dragenter', dragEnter);
  j.addEventListener('dragleave', dragLeave);
  j.addEventListener('drop', Drop);
}

function Drop() {
  if (this.querySelector('#' + dragItem.id)) {
    return;
  }
  this.append(dragItem)
}

function dragOver(e) {
  e.preventDefault()
}

function dragEnter(e) {
  e.preventDefault()
}

function dragLeave() {}
.choice {
  float: left;
  margin: 5px;
  border: 1px solid #bbb;
  padding: 5px;
}

.choice p {
  border: 1px solid #bbb;
}
<h1>Rank in order as your choice</h1>
<section>
  <div class="choice">
    <p id="green" draggable="true">Green</p>
    <p id="orange" draggable="true">Orange</p>
    <p id="purple" draggable="true">Purple</p>
  </div>
  <div class="choice">
    <p id="yellow" draggable="true">Yellow</p>
    <p id="green" draggable="true">Green</p>
    <p id="orange" draggable="true">Orange</p>
  </div>
  <div class="choice">
    <p id="pink" draggable="true">Pink</p>
    <p id="skyblue" draggable="true">Skyblue</p>
    <p id="purple" draggable="true">Purple</p>
  </div>

</section>

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

Dynamic content in a CSS animation that rolls credits as they scroll

Currently, I'm working on creating a credit scrolling effect that pulls data from the JustGiving API to display a list of donors. I have successfully populated the list of donors and connected to the API without any issues. However, the challenge lies ...

Sass error: Unable to locate the stylesheet for import while trying to import bootstrap

I am currently working on integrating bootstrap into my project directory using npm. Below is an overview of my file structure: https://i.sstatic.net/HjExY.png Within my style.scss file, I am utilizing the @import feature to include Bootstrap as follows: ...

The function Router.use is looking for a middleware function, but instead received an object in node.js /

I encountered an issue while trying to setup routing in my application. Whenever I attempt to initialize a route using app.use() from my routes directory, I receive an error stating that Router.use() requires a middleware function but received an Object in ...

Can the image upload file size be customized or adjusted?

Recently, I've come across a standard input file code that looks like this: <Label class="custom-file-upload"> <input type="file" onChange={onDrop} /> Upload Photo </Label> I have been thinking about limiting the size of the ...

How can one access the owner function from a different function?

Check out the example on jsfiddle: https://jsfiddle.net/cg33ov4g/3/ (function($){ var foo='foo_value'; var bar='bar_value'; function getVar(theVar){ console.log(this[foo]); console.log(this[bar]); //the c ...

Focusing on a particular iframe

I am currently using the "Music" theme from Organic Theme on my WordPress site and have inserted this code to prevent SoundCloud and MixCloud oEmbeds from stretching the page width: iframe, embed { height: 100%; width: 100%; } Although the fitvid ...

Dynamic Visibility Control of GridPanel Header in ExtJS

I have a GridPanel that needs to display a limited number of resources. If there are more resources available than what is currently shown, I would like the panel's header/title to indicate this by displaying text such as "more items available - displ ...

What is the best way to upload an image through PHP using $_POST after using JavaScript to resize it?

I am currently working on developing a webpage that allows users to upload images from their iPhone, Android, and desktop devices. The goal is to save these pictures as thumbnails in the ./userupload directory and store the link to them in a MySQL database ...

Eliminate repeated elements in a selection using an AngularJS custom directive

I am in the process of creating an events app that utilizes JSON data from Drupal to showcase events using AngularJS within a Drupal module. One of the keys in the JSON object is 'genre', which I'm utilizing in a select dropdown to allow use ...

Breaking down an array into groups - where did I go wrong in my code?

Check out the following code : function splitArrayIntoGroups(arr, size) { // Splitting the array into groups. var newArray = []; for(var i = 0; i < arr.length; i++){ for(var j = 0; j < size; j++){ newArray.push(arr.splice(0, size)); ...

Attempting to design a unique CSS ribbon but hitting a roadblock with getting the perfect curve just right

I have attempted to create a CSS shape (ribbon) using border radius, but I am struggling to achieve the desired curve. The curve I manage to create does not exactly match the curve of the div in the image. background: #008712; width: 89px; height: 22p ...

Working with AngularJS $resource: including an array element in paramDefaults

I'm currently working with the twitch.tv API and utilizing the Angular $resource factory. My goal is to access the endpoint: GET /channels/:channel. What I want to achieve is to retrieve the channel for each element within an array. I attempted using ...

Configuring babel-loader in webpack for optimal HMR functionality

Recently, I encountered an issue while trying to add Hot Module Replacement (HMR) to my project. Despite the console showing that HMR was enabled and detecting changes in files, the view was not re-rendering. The console would display: [HMR] Updated modul ...

Retrieve the username of a specific User from the Django model

Wondering if there may be a duplicate question, but I couldn't locate it Here is the code snippet from models.py # Define user profile information model class UserProfileInfo(models.Model): # Set up one-to-one relationship with User model use ...

How can I insert an empty option following a selected value in a dropdown menu using jQuery?

How to use jQuery to insert a blank option after an existing option? I attempted to add a blank option, but it ended up at the top of the dropdown. I actually need one existing option followed by one blank option. For example: <option></option& ...

Tooltipster fails to function with elements that are dynamically created

I've been struggling with this issue for several days now, but I can't seem to find a solution. In my JavaScript code, I have a function that generates HTML after an Ajax call is completed. I call this function in the following manner: $(documen ...

IE11 blocking .click() function with access denied message

When attempting to trigger an auto click on the URL by invoking a .click() on an anchor tag, everything works as expected in most browsers except for Internet Explorer v11. Any assistance would be greatly appreciated. var strContent = "a,b,c\n1,2,3& ...

Is there a way to serve an HTML file using the response object in expressjs while also incorporating an external JavaScript file?

My express application successfully serves an HTML page from my disk when I initially make a GET request to "http://localhost:3000/" in the browser. Now, I am trying to access a JavaScript file that is located in the same directory on the disk as the HTML ...

Loading hover images in css through jQuery preloading

Is there a reliable method for preloading CSS hover images using jQuery that anyone knows of? My ideal scenario would involve adding a class (for example, "pre-load-hover") to any element needing preloading, and then implementing JavaScript in $(document) ...

Retrieving outcomes from a sequence of callback functions in Node.Js

I've been struggling to get my exports function in Node.Js / Express app to return the desired value after going through a series of callback functions. I've spent hours trying to fix it with no success. Can someone provide some guidance? Here is ...