Having trouble with my code trying to transfer elements back and forth between two unordered lists using an "addEventListener"

I have developed a task management system where users can create a to-do list for their daily tasks. Upon completion of a task, they can tick the checkbox next to it, which will trigger a strikethrough effect. The completed tasks are then moved from the "uList" unordered list to the "taskCompleted" unordered list. Additionally, I want to give users the ability to move a task back from "taskCompleted" to "uList" by simply double-clicking on it. The task should revert to its original state with no strikethrough and an unchecked checkbox. I have attempted to achieve this using the event object and a for loop, but so far, both attempts have failed. I am eager to receive feedback on this implementation.

var elUlList = document.getElementById("uList");
var btn = document.getElementById("btn");
const elInput = document.getElementById("input");
const footer = document.querySelector("footer");
const message = document.getElementById("message");
const elCounter = document.getElementById("counter");
const taskCompleted = document.getElementById("taskCompleted");
var elements = document.getElementsByTagName("li");
var input = document.getElementsByTagName("input")

function createListItems() {
  var inputValue = elInput.value;
  if(inputValue === "" || inputValue === null) return

  var newLi = document.createElement("li");
  newLi.id = Date.now().toString();
  var input = document.createElement("input");
  input.type = "checkbox";
  input.name = "to-do-input";
  var newText = document.createTextNode(inputValue);
  newLi.appendChild(input);
  newLi.appendChild(newText);
  elUlList.appendChild(newLi);
  elCounter.innerHTML =+ elements.length;

  var toDoInput = document.getElementsByTagName("to-do-input");

  for(var i = 0; i < toDoInput.length; i++) {
    toDoInput[i].addEventListener("change", function(e) {
      if(e.target.checked == true) {
        e.target.parentNode.remove();
      }
    })
  }
  }

btn.addEventListener("click", createListItems, false);

elInput.addEventListener("keyup", function(e) {
  if(e.keyCode === 13) {
    e.preventDefault();
    btn.click()
  }
})

elInput.addEventListener("mouseover", emptyField, false)

function emptyField() {
  this.value = "";
}

elUlList.addEventListener("change", function(e){
  var target = e.target;
  var parent = target.parentNode;
  alert("are you sure you want to move this item to completed task");
  parent.classList.add("taskMoved");
  taskCompleted.appendChild(parent);
  elCounter.innerHTML =+ elements.length;
});


elUlList.addEventListener("click", strikeOutElement, false);


function strikeOutElement(e) {
  var target = e.target;
  if(target.matches("input[type=checkbox]")){
  target.closest("li").classList.toggle("lineThrough", target.checked);
  }
}

var taskMoved = document.getElementsByClassName("taskMoved");

if(taskMoved.length > 0) {
  for(var i = 0; i < taskMoved.length; i++) {
    taskMoved[i].addEventListener("dblclick", function() {
    taskMoved[i].classList.remove("lineThrough");
    taskMoved[i].firstElementChild.toggle("lineThrough", target.checked);
    taskMoved[i].firstElementChild.checked = false;
    elUlList.appendChild(taskMoved[i]);
  }, false);
  }
}
var date = new Date().toLocaleDateString("en-US")

footer.innerHTML = date
console.log(date)
.greenColor {
  color: green;
}

.redColor {
  color: red;
}

.lineThrough {
  text-decoration: line-through;
}

li {
  list-style-type: none;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">

  <head>
    <meta charset="utf-8">
    <title>Practise App</title>
    <link rel="stylesheet" href="index.css">
  </head>
  <body>

  <div id="message"class=""></div>
  <ul id="uList"></ul>
  <button id="btn" type="button" name="button">click here to add items</button><br>
  <input id="input" type="text" name="" value="">
  <div id="counter" class=""></div>
  <p>task Completed</p>
  <ul id="taskCompleted"></ul>

  <footer></footer>


    <script src="index.js" type="text/javascript"></script>
  </body>
</html>

Answer №1

You seem to have a lot of global variables and event listeners scattered throughout your code. I have refactored it to be more efficient, with just one function handling the task creation and management with only 2 listeners.

const tasksTodo = document.getElementById("uList");
var btn = document.getElementById("btn");
const elInput = document.getElementById("input");
const footer = document.querySelector("footer");
const message = document.getElementById("message");
const elCounter = document.getElementById("counter");
const tasksCompleted = document.getElementById("taskCompleted");
var elements = document.getElementsByTagName("li");
var input = document.getElementsByTagName("input");

function createTask(input) {
  let title = input.value;
  if ( !title ) return false;
  let task = document.createElement("li");
  let checkbox = document.createElement("input");
  checkbox.type = "checkbox";
  task.appendChild(checkbox);
  task.appendChild(document.createTextNode(title));

  //Checkbox is the source of truth, listening to change event
  checkbox.addEventListener("change", e => {
      if (checkbox.checked)
        completeTask(task);
      else
        undoTask(task);
  });
  tasksTodo.appendChild(task);
  //Allow dblclick to toggle the checkbox
  task.addEventListener("dblclick", e =>{checkbox.click()});
  //reset the input after task creation
  input.value = '';
}

function completeTask(task) {
  task.classList.add("lineThrough");
  tasksCompleted.appendChild(task);
}

function undoTask(task) {
  task.classList.remove("lineThrough");
  tasksTodo.appendChild(task);
}

btn.addEventListener("click", e=>{createTask(elInput)}, false);
elInput.addEventListener("keyup", function(e) {
  if (e.keyCode === 13) {
    e.preventDefault();
    btn.click();
  }
});

var date = new Date().toLocaleDateString("en-US");

footer.innerHTML = date
console.log(date)
.greenColor {
  color: green;
}

.redColor {
  color: red;
}

.lineThrough {
  text-decoration: line-through;
}

li {
  list-style-type: none;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8>
  <title>Practise App</title>
  <link rel="stylesheet" href="index.css">
</head>

<body>

  <div id="message" class=""></div>
  <ul id="uList"></ul>
  <button id="btn" type="button" name="button">click here to add items</button><br>
  <input id="input" type="text" name="" value="">
  <div id="counter" class=""></div>
  <p>task Completed</p>
  <ul id="taskCompleted"></ul>

  <footer></footer>


  <script src="index.js" type="text/javascript"></script>
</body>

</html>

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 best way to retrieve a value from an object using a promise after a certain period of time

During an event, I receive a user object. When I try to access the user._properties.uid value before using setTimeout, it returns as undefined. However, when I implement setTimeout, the value is successfully fetched after a few seconds. Is there a way to ...

We encountered an error while trying to locate the 'socket.io' view in the views directory

Having an issue with my nodejs server. Check out the code below: server.js global.jQuery = global.$ = require('jquery'); var express = require('express'), path = require('path'), menu = require("./routes/menu"); var ...

Step-by-step guide on dynamically fetching additional images from a directory using php, jquery, and ajax

I have a scenario where I have multiple folders, each containing up to 20 images. On my HTML page, I want to display the first 5 images and provide a "click to view more" option to show the remaining 15 images when clicked. Currently, the issue I am facin ...

Order of flexbox items when placed within separate divs?

Looking to rearrange the order of items using flexbox, but hitting a roadblock because one of the items I want to reorder is in a different div and not a direct child of the same parent as the other items. <div class="wrapper"> <div class="some ...

Dynatree experiences sluggish performance when loading over 100 nodes dynamically

How can I improve the loading speed? I am retrieving data from a JSON web service very quickly. However, when I add nodes to the tree using the following code: parentNode.addChild({ key: key, title: value, addClass: cssClass } ...

Position footer at the bottom of the webpage and adjust the height to be filled with main content using Bootstrap 4

I am currently in the process of designing a bootstrap layout that includes a header navbar along with a footer. My goal is to ensure that the footer is always at the bottom of the page, even if there is limited content. Here's what I have implemente ...

Buffer Overflow - Security Audit - Node JS TypeScript Microservice Vulnerability Scan Report

Person Data Schema: import JoiBase from '@hapi/joi'; import JoiDate from '@hapi/joi-date'; const Joi = JoiBase.extend(JoiDate); const personDataSchema = Joi.object().keys({ person: Joi.object().keys({ personId: Joi.string().max( ...

What is the best way to toggle a div and dynamically load content into it while it's open?

I am looking to create a toggle effect where a div opens, loads a page within it, and then can be closed again. My goal is to achieve this functionality with multiple links on the page. <div id="main-nav"> <div id="menu-container"&g ...

Issue: Encounter of an unexpected token (Please ensure that plugins are installed to import files that are not JavaScript) while using the rollup vue package

I am working on creating a Vue component library, but I encountered an error with my type checking. I attempted to update TypeScript as mentioned here, but it did not resolve the issue. Here is a snippet of my code and `package.json` file. My component cod ...

Clicking anywhere outside a popup menu in JavaScript will deactivate a toggle and hide it

I have three different menu options: home,Clinic, and About. When I click on the Clinic option, a Megamenu appears, and if I click on it again, the Megamenu is hidden. I want the Megamenu to hide when clicking anywhere on the webpage. The issue is that cu ...

The driver instance that has forked will never cease

Issues arise when attempting to run multiple browser windows in Protractor. The code snippet being tested is as follows: I create a new browser instance to perform certain tests. When input is entered into the original browser, it should not affect the ne ...

When a div slides down on page load, the div will slide up when a button is clicked

I am trying to make a div slideDown on page load. The goal is to have the div automatically slideDown after 2 seconds, which contains a responsive image and a button named "z-indexed". However, I am having trouble getting the same div to slideUp when the z ...

What is the best way to add HTML formatted text into Outlook?

In my Emacs, I've generated this syntax-highlighted code snippet and now want to paste it into an Outlook email with rendered HTML (without the actual HTML code). <pre> <span style="color: #a020f0; background-color: gtk_selection_bg_color;"& ...

The Heroku application is rendering with different CSS and positioning compared to the local development environment

My locally hosted site has correct CSS and positioning, but once deployed to Heroku, it appears to lose some of its CSS styles. I am using the MERN Stack for this project. I suspect that the issue may be related to my node_modules, even though I have them ...

What methods are most effective for verifying user credentials in a web application using Node.js and AngularJS?

Currently, I am working on a project that involves using Node.js and MySQL for handling user data. I would like to leverage the user information stored in the MySQL database, but I am unsure about the most secure method for implementing user authentication ...

The functionality of a pop-up window is not compatible with Google Maps

I recently implemented a script on my webpage that triggers a popup window every time the page is loaded. Here's how the script looks: <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>ColorBox de ...

Retrieve an item fetched from the database using Javascript in MVC4 framework

How can I access the properties of an object returned from a database using JavaScript? This JavaScript function is invoked: function searchUser() { var userName = document.getElementById('UserName').value $.post("SearchForUser", { user ...

Issue encountered while validating a dropdown selection within a form using JavaScript

I have a form that includes multiple options for users to choose from. My goal is to prevent users from selecting the same option more than once. I've written some JavaScript code for this purpose, but I'm encountering an issue with the alert mes ...

Exploring the world of three.js, webGL, and GLSL through the magic of random

When using three.js to call a fragment shader, I have a shader that specifies a color for my material in rgb format. I am trying to figure out a way to multiply those colors by a random value. The code I currently have is as follows: gl_FragColor = vec4( ...

Finding the console path in node.js

I'm currently developing a console application for node.js and I could use some guidance. When users install my console app using 'npm', they should be able to call it by typing 'program'. However, if the console is located at C:/U ...