Nothing remains after the fall: coding void

I am facing an issue where my item becomes null after being dragged 2-3 times and dropped in a different place. I have included my code below and I can't seem to figure out where the mistake lies. Can you please review it and let me know what needs to be fixed? This is my first time using Drag & Drop functionality, so I might be missing something.

View code here

    function updateStyle() {

//get list items and lists

  const list_items = document.querySelectorAll('.list-item');
  const lists = document.querySelectorAll('.list');

//iterate through list items 

  let draggedItem = null;
  for (let i = 0; i < list_items.length; i++) {
    const item = list_items[i];

//make items draggable

    item.addEventListener('dragstart', function () {
      // console.log("dragstart")
      draggedItem = item;
      setTimeout(function () {
        item.style.display = 'none';
      }, 0);
    });

//end dragging item

    item.addEventListener('dragend', function () {
      // console.log("dragend")
      setTimeout(function () {
        draggedItem.style.display = 'block';
        draggedItem = null;
      }, 0);
    });

//loop through lists

    for (let j = 0; j < lists.length; j++) {
      const list = lists[j];
      // console.log('list ', list);
      //allow item to be dragged over 
      list.addEventListener('dragover', function (event) {
        event.preventDefault();
      });

//when entering draggable zone

      list.addEventListener('dragenter', function (event) {
        event.preventDefault();
        this.style.backgroundColor = 'rgba(0, 0, 0, 0.2)';
      });

//leave the zone and remove color

      list.addEventListener('dragleave', function (event) {
        this.style.backgroundColor = 'rgba(0, 0, 0, 0.1)';
      });

 //dropping in the zone

      list.addEventListener('drop', function (event) {

//set background color in drop zone

        this.style.backgroundColor = 'rgba(0, 0, 0, 0.1)';
        this.append(draggedItem);
      });
    }
  }
}

//create a new list

function createList(event) {
  event.preventDefault();

 //get title text

  const titleText = document.getElementById('titleText');
  console.log('titleText', titleText);

//if input is empty alert ....if not

  if (titleText.value.length === 0) {
    alert('task cannot be empty, please add a title');
    return;
  }


//creating and appending the element

  const lists = document.getElementById('lists');
  const list = createElement('div', '', 'list');
  const title = createElement('h3', titleText.value, 'list-title');
  const id = `task-${titleText.value}-list`;
  list.id = id;
  list.append(title);
  lists.append(list);
  const taskInput = createTaskInput(titleText.value);
  list.append(taskInput);
  titleText.value = '';
  updateStyle();
}

//create Element

function createElement(tag, text, className = null) {
  const element = document.createElement(tag);
  console.log('element', element);

 //add classList if classname exists

  if (className) {
    console.log('className', className);
    element.classList.add(className);
  }
  if (text && text.length > 0) {
    const textNode = document.createTextNode(text);
    element.appendChild(textNode);
  }
  return element;
}

//create new Task Input and append input and button

function createTaskInput(listName) {
  const form = createElement('form', '', 'task-form');
  const input = createElement('input', '');
  const button = createElement('button', '');
  const id = `task-${listName}`;
  input.name = 'task';
  input.id = id;
  button.innerText = 'Add';
  button.addEventListener('click', function (event) {
    event.preventDefault();
    addTaskListItem(id);
  });
  form.append(input);
  form.append(button);
  return form;
}

//add task list item

function addTaskListItem(id) {

  //get element by id

  const task = document.getElementById(id);

  //creating new task in block

  console.log('task ', task);
  if (task.value.length === 0) {
    alert('Cannot be empty');
    return;
  }
  const list = document.getElementById(`${id}-list`);
  const listItem = createElement('div', task.value, 'list-item');
  listItem.setAttribute('draggable', true);
  task.value = '';
  list.append(listItem);
  updateStyle();
}

*Feel free to provide feedback on any potential issues*

Answer №1

After troubleshooting, I finally discovered my error in the setTimeout function. It turns out that in the "dragend" event, I mistakenly added:

draggedItem = null;

Such a silly mistake on my part! Here is the corrected code snippet:

//finish draggable item 

item.addEventListener('dragend', function () {
  // console.log("dragend")
  setTimeout(function () {
    draggedItem.style.display = 'block';
    draggedItem = null;
  }, 0);
});

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

What is the reason for JSHint alerting me about utilizing 'this' in a callback function?

While working in my IDE (Cloud 9), I frequently receive warnings from JSHint alerting me to errors in my code. It is important to me to address these issues promptly, however, there is one warning that has stumped me: $("#component-manager tr:not(.edit-co ...

What is the best way to translate this code into JQuery ajax?

I have some code here that is currently using Javascript AJAX. I'm interested in converting it into jQuery AJAX, can someone help me with this? var mine = new XMLHttpRequest(); mine.onreadystatechange = function() { if (mine.readyState == 4 &am ...

Challenges with login pages integrating JS/JQuery and Firebase

I've been working on creating a login page where once the user successfully logs in, I want to make it so that they are redirected from the index.html page to my portfolio.html page. firebase.auth().onAuthStateChanged(user => { if(user) { wind ...

Incorporating a delay into looped HTTP requests while effectively utilizing Promise.all to track their completion

Greetings! In my current project, I am trying to introduce a 50ms delay before each subsequent HTTP request is sent to the server. Additionally, I aim to incorporate a functionality that triggers after all requests have been successfully made. To better e ...

Updating data in a VueJS Single File Component

I'm finding myself in a bit of a maze when it comes to understanding how data functions within single file components for VueJS. For instance, in a file named test.vue, my understanding is that you would script something like this: export default { ...

Tips on downloading an image using the URL in nestjs

I'm trying to retrieve a link and save the associated image in the static folder, but I seem to be encountering some issues with my code. Here's what I have so far: @Injectable() export class FilesService { createFileFromUrl(url: string) { t ...

Creating dynamic web pages with jQuery is a simple and effective

I am currently using jQuery to create HTML elements with specific classes and then append them together. However, the code I have written is not adding the generated HTML to the container as expected. There are no errors being produced but the HTML is not ...

What is the process of incorporating events into a calendar using jQuery or JavaScript?

$(document).ready(function () { //initialize calendar $(".responsive-calendar").responsiveCalendar({ time: '2016-02', events: { "2016-03-30": {"number": 5, "url": "http://w3widgets.com/responsive-slider"}, "201 ...

The issue of Rails time lagging by a day persists upon deployment on my server

When a user clicks on a day in my calendar, I pass a JavaScript time variable to my Rails controller using Ajax. Everything works perfectly when I test it locally, but once deployed on the server, the date appears to be one day behind the actual day click ...

Execute a function (with arguments) within a v-for loop in Vue.js

Currently, I am attempting to create a select element using Vue.js and Material Design that has 2 levels: categories and items. Each category can contain multiple items which may be selected or not. <md-select v-if="categories.length > 0" name="cate ...

The issue arises in Selenium IDE when a variable is mistakenly identified as a string instead of a

Hey there, I've encountered an issue while using Selenium IDE. I'm trying to increment a variable by two, but instead of performing numerical addition, it seems to be concatenating strings. <tr> <td>store</td> <td> ...

Stop the infiltration of emotions into your style

Utilizing the JsonForms React Component to dynamically generate an HTML form in my web application. The framework I am using handles all view rendering on the server side. To integrate this component, I compiled a small react component by running npm run b ...

Methods for sending data from Angular to the server and vice versa

Currently, I have an application that utilizes Express along with Jade templates. I am in the process of developing a new version of the app using Angular and client-side HTML. In order to determine user permissions within my Angular code, I require acces ...

The presence of a default value within an Angular ControlValueAccessor triggers the dirty state due to

My task is to create dynamic Input components for a template driven form using a directive. The default value of the Input component should be set by the component itself. However, I encountered an issue where setting a default value automatically marks t ...

Need some assistance in finding a way to input multiple values from multiple buttons into a single input field in JavaScript

Hello, I am looking for a little help with reading multiple values using multiple buttons such as 1, 2, and 3, and displaying the output in the input like '123' instead of just one number at a time. Concatenate numbers with every click. <inpu ...

Converting an array of object values to an Interface type in Typescript

In my JSON document, I have an array named dealers that consists of various dealer objects like the examples below: "dealers" : [ { "name" : "BMW Dealer", "country" : "Belgium", "code" : "123" }, { "name" : ...

Comparing Encrypted Passwords with Bcrypt

Encountering an issue with comparing passwords despite accurately storing the hashed password during registration. Database - MongoDB Node.js version - v18.17.0 Bcrypt version - 5.1.1 Below is my userSchema: const userSchema = new mongoose.Schema({ u ...

Navigating to a precise location on a webpage with React.js

I want to implement a straightforward action where the page automatically scrolls to a specific position upon loading. However, my attempts to execute this action have been unsuccessful so far. Is there an alternative method to achieve this in a React ap ...

Retrieving a universal variable within AngularJS

Is there a way to initialize an Angular model using a JSON object that is embedded within an HTML page? Take this as an example: <html> <body> <script type="text/javascript" charset="utf-8"> var tags = [{&q ...

Incorporating CouchDB storage into a Node.js socket.io JSON data stream

Currently in the process of researching how to implement persistence for a real-time Twitter JSON feed in Node.js. The stream is set up and sending data to the client, but I'm struggling with storing this information in a CouchDB database so that it c ...