skip to Main Content

What I want to do is when I click the task it will have a line through the text means that I’m done with the task. but the add event listener function for this is not working, I’m working with the javascript toggle and that’s all I can think of right now to achieve this functionality.

Is there another way to do this? I searched on the internet and it seems complicated when I’m trying to figure it out.

const addBtn = document.querySelector("#push");
const taskInput = document.querySelector("#taskInput");
const taskOutput = document.querySelector("#tasks");

addBtn.addEventListener("click", function() {
  let newTasks = taskInput.value;
  if (newTasks.length == 0) {
    alert("Please enter a task");
  } else {
    taskOutput.innerHTML += `<div class="task">
                <span id="taskname">${newTasks} </span>
                <button class="delete" id="deleteButton"><i class="fa-solid fa-trash"></i> </button>
    
    
            </div>
            `;
    //delete
    let deleteBtn = document.querySelector("#deleteButton");
    deleteBtn.addEventListener("click", function() {
      this.parentNode.remove();
    });
    //line through
    let theTask = document.querySelectorAll(".task");
    theTask.addEventListener("click", function() {
      this.classList.toggle("completed");
    });
  }
});
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body {
  height: 100vh;
  background: linear-gradient( 90deg, rgba(241, 206, 221, 1) 0%, rgba(124, 184, 254, 1) 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: 'Kumbh Sans', sans-serif;
}

.container {
  border: 2px solid white;
  width: 50%;
  min-width: 450px;
  margin: auto;
  padding: 30px 40px;
}

#new-task {
  position: relative;
  background-color: white;
  padding: 30px 20px;
  border-radius: 1em;
}

#new-task input {
  width: 70%;
  height: 45px;
  font-family: 'Manrope', sans-seif;
  font-size: 1.2em;
  border: 2px solid #d1d3d4;
  padding: 12px;
  color: #111111;
  font-weight: 500;
  position: relative;
  border-radius: 5px;
}

#new-task input:focus {
  outline: none;
  border-color: violet;
}

#new-task button {
  font-family: 'Manrope', sans-seif;
  position: relative;
  float: right;
  width: 25%;
  height: 45px;
  border-radius: 5px;
  font-weight: bold;
  font-size: 16px;
  border: none;
  background-color: violet;
  color: white;
  cursor: pointer;
}

#tasks {
  background-color: white;
  padding: 30px 20px;
  margin-top: 50px;
  border-radius: 10px;
  width: 100%;
}

.task {
  background-color: white;
  height: 50px;
  padding: 5px 10px;
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 2px solid violet;
  cursor: pointer;
}

.task span {
  font-size: 18px;
  font-weight: 400;
}

.task button {
  background-color: violet;
  color: white;
  height: 100%;
  width: 40px;
  border: none;
  border-radius: 5px;
  outline: none;
  cursor: pointer;
}

.task button:hover {
  background-color: red;
}

.completed {
  text-decoration: line-through;
}
<body>
  <div class="container">
    <div id="new-task">
      <input type="text" name="" id="taskInput" placeholder="Task to be done" />
      <button id="push">ADD</button>
    </div>


    <div id="tasks"></div>
  </div>

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

3

Answers


  1. theTask is a list of nodes. Trying to attach event listener on this list is causing issues.

    Also, you will be inserting lots of buttons with same id deleteButton and spans with same id taskname which is incorrect and can cause undefined behavior.

    For theTask fix, you may want to do something like:

    let theTasks = [...document.querySelectorAll(".task")];
    theTasks.forEach(task => {
      task.addEventListener("click", function() {
        this.classList.toggle("completed");
      })
    });
    
    Login or Signup to reply.
  2. querySelectorAll will return the list of nodes matching the selector tasks. So you have to iterate through each of those nodes and add your listener. See the below code snippet

    let theTasks = document.querySelectorAll(".task");
    theTasks.forEach((task) => {
      task.addEventListener("click", function() {
        this.classList.toggle("completed");
      });
    });
    
    Login or Signup to reply.
  3. Using innerHTML to create manipulate the DOM for an application like a todo list is probably not a good idea. The answers to Advantages of createElement over innerHTML? give good explanations why.

    It is worth noting that in the innerHTML code, the span and the button are created with an id and so all of these elements will have the same id. It is also probably not a good idea to have duplicate ids on one page. Why are duplicate ID values not allowed in HTML? explains why.

    Also, adding event listeners to every new task is also probably not a good idea. What is DOM Event delegation? gives a good explanation why.

    Finally, the Difference between HTMLCollection, NodeLists, and arrays of objects and Document.querySelectorAll() explain how to get lists of elements that can be manipulated.

    So, I have rewritten the task creation code in the addBtn.addEventListener to show one way how this could be done with document.createElement().

    And I have created a separate event listener on the Tasks container div, which handles both task deletion and task completion.

    I also added the following CSS so that clicking on a trash can icon is handled by the parent button. Without this CSS, clicking on an icon would not delete the task.

    div#tasks i {
      pointer-events: none;
    }
    

    To make the todo list more visible in the code snippet below, I reduced the heights, margins, and paddings of some of the elements in the CSS.

    I also added a link to the font awesome icon library.

    const addBtn = document.querySelector("#push");
    const taskInput = document.querySelector("#taskInput");
    const taskOutput = document.querySelector("#tasks");
    
    taskOutput.addEventListener("click", function(event) {
      if (event.target && event.target.nodeName === "SPAN") {
        event.target.classList.toggle("completed");
      }
      if (event.target && event.target.nodeName === "BUTTON") {
        event.target.parentNode.remove();
      }
    });
    
    addBtn.addEventListener("click", function() {
      let newTasks = taskInput.value;
      if (newTasks.length == 0) {
        alert("Please enter a task");
      } else {
        //  Create a task DIV
        const newTaskElement = document.createElement("div");
        newTaskElement.classList.add("task");
    
        //  Create a SPAN with the task name 
        const newTaskNameElement = document.createElement("span");
        const taskTextnode = document.createTextNode(newTasks);
        newTaskNameElement.appendChild(taskTextnode);
    
        //  Create a BUTTON with a TRASH CAN ICON 
        const newTaskDeleteButton = document.createElement("button");
        const deleteImageElement = document.createElement("i");
        deleteImageElement.classList.add("fa-solid", "fa-trash");
        newTaskDeleteButton.appendChild(deleteImageElement);
    
        //  Append the SPAN and the BUTTON to the task DIV
        newTaskElement.appendChild(newTaskNameElement);
        newTaskElement.appendChild(newTaskDeleteButton);
    
        //  Append the task DIV to the TASK LIST DIV
        taskOutput.appendChild(newTaskElement);
      }
    });
    * {
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }
    
    body {
      height: 100vh;
      background: linear-gradient( 90deg, rgba(241, 206, 221, 1) 0%, rgba(124, 184, 254, 1) 100%);
      font-family: 'Kumbh Sans', sans-serif;
    }
    
    
    /* ADDED TO MAKE SURE THAT THE TRASH ICON DOES NOT PROCESS CLICKS */
    
    div#tasks i {
      pointer-events: none;
    }
    
    .container {
      border: 2px solid white;
      width: 50%;
      min-width: 450px;
      margin: auto;
      padding: 3px 4px;
    }
    
    #new-task {
      position: relative;
      background-color: white;
      padding: 6px 4px;
      border-radius: 1em;
    }
    
    #new-task input {
      width: 70%;
      height: 45px;
      font-family: 'Manrope', sans-seif;
      font-size: 1.2em;
      border: 2px solid #d1d3d4;
      padding: 12px;
      color: #111111;
      font-weight: 500;
      position: relative;
      border-radius: 5px;
    }
    
    #new-task input:focus {
      outline: none;
      border-color: violet;
    }
    
    #new-task button {
      font-family: 'Manrope', sans-seif;
      position: relative;
      float: right;
      width: 25%;
      height: 45px;
      border-radius: 5px;
      font-weight: bold;
      font-size: 16px;
      border: none;
      background-color: violet;
      color: white;
      cursor: pointer;
    }
    
    #tasks {
      background-color: white;
      padding: 6px 4px;
      margin-top: 5px;
      border-radius: 10px;
      width: 100%;
      min-height: 50px;
    }
    
    .task {
      background-color: white;
      height: 50px;
      padding: 5px 10px;
      margin-top: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 2px solid violet;
      cursor: pointer;
    }
    
    .task span {
      font-size: 18px;
      font-weight: 400;
    }
    
    .task button {
      background-color: violet;
      color: white;
      height: 100%;
      width: 40px;
      border: none;
      border-radius: 5px;
      outline: none;
      cursor: pointer;
    }
    
    .task button:hover {
      background-color: red;
    }
    
    .completed {
      text-decoration: line-through;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css" rel="stylesheet" />
    <div class="container">
      <div id="new-task">
        <input type="text" name="" id="taskInput" placeholder="Task to be done" />
        <button id="push">ADD</button>
      </div>
      <div id="tasks"></div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search