The CSS element remains inactive

Just starting out with Css and javascript, I'm currently engaged in a simple project (similar to a weekly task manager). On my text/html page, I have a navbar, 7 dynamic <ul> elements with "Add task" and "Delete Task buttons", and each <li> element inside these lists can change its state to .active when clicked (to mark the task as done). The issue arises when I try to use JavaScript and a button to add a new <li>; it simply won't become active.

function addTask() {
  var ul = document.getElementById("mondayList")
  var li = document.createElement("li")
  li.className = 'todo'
  li.appendChild(document.createTextNode("TaskName"));
  ul.appendChild(li);
}
const todos = document.querySelectorAll(".todo");
const togglers = document.querySelectorAll(".toggler");


todos.forEach((todo) => {
  todo.addEventListener("click", () => {
    todo.classList.toggle('active');
  })
})

togglers.forEach((toggler) => {
  toggler.addEventListener("click", () => {
    toggler.classList.toggle('active');
    toggler.nextElementSibling.classList.toggle('active');
  })
})
.todos {
  font-family: "Segoe UI fw-semibold", Tahoma, serif;
  font-size: 1.5rem;
  padding: 5rem;
}

ul {
  list-style-type: none;
}

.todos {
  cursor: pointer;
}

.todo::before {
  content: "\2610";
  display: inline-block;
  margin-right: 0.5rem;
}

.todo.active::before {
  content: "\2611";
}

.todo.active {
  text-decoration: line-through;
  color: #888;
}

.toggler::before {
  content: "\25B6";
  display: inline-block;
  margin-right: 0.5rem;
  transition: transform 0.3s ease-in-out;
}

.toggler.active::before {
  transform: rotate(90deg);
}

.toggler-target {
  display: none;
}

.toggler-target.active {
  display: inline-block;
}
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a7c5c8c8d3d4d3d5c6d7e79288958997">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-gH2yIJqKdNHPEq0n4Mad/HGKIhSkIHeL5AyhkYV8i59U5AR6csBvApHHNl/kI1Ox" crossorigin="anonymous" />
<link href="/css/style.css" rel="stylesheet">
<!------Scripts for Navbar Deployment-->
<script src="https://cdn.jsdelivr.net/npm/@popperjs/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dbb9bcc0cdbfbdebfccdfadeAB84bcdadfd0dcfed3CDCDEEB42edfccda0fdfafa">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-Xe+8cLOoJaPtN/veChSPwrqv+lEajZBovgmPmFeFZWalmDVntaaPaJvnYZsggxdPhA" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="57354358555d444052630b14510b0b15">[email protected]</a>/dist/js/bootstrap.min.js" integrity="sha384-ODmDIVzU+FuSQxeeHeFiOiIvjRNapGYEyqaDcqOhhciBlLtqhTsoPsToQdlbRicUzyK" crossorigin="anonymous"></script>

<nav class="navbar navbar-expand-lg bg-light">
  <div class="container">
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link" aria-current="page" href="/home">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link active" href="/test">InobitecTest </a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="unfold">
  <button class="btn btn-dark">[+]Unfold[+]</button>
</div>
<div style="margin: auto">
  <ul class="todos" id="todos" style="display: inline-block;margin-left: 786px;padding-top: 0px">
    <li>
      <div class="toggler">Monday</div>
      <ul class="toggler-target" id="mondayList">
        <li>
          <a class="btn btn-primary fw-light" onclick="addTask()">Add Task</a>
          <a class="btn btn-danger fw-light">DeleteTask</a>
        </li>
        <li class="todo">Task1</li>
      </ul>
    </li>
    <li>
      <div class="toggler" id="tuesdayList">Tuesday</div>
      <ul class="toggler-target">
        <li>
          <a class="btn btn-primary fw-light">Add Task</a>
          <a class="btn btn-danger fw-light">DeleteTask</a>
        </li>
      </ul>
    </li>
    <li>
      <div class="toggler" id="wednesdayList">Wednesday</div>
      <ul class="toggler-target">
        <li>
          <a class="btn btn-primary fw-light">Add Task</a>
          <a class="btn btn-danger fw-light">DeleteTask</a>
        </li>
      </ul>
    </li>
    <li>
      <div class="toggler">Thursday</div>
      <ul class="toggler-target" id="thurstdayList">
        <li>
          <a class="btn btn-primary fw-light">Add Task</a>
          <a class="btn btn-danger fw-light">DeleteTask</a>
        </li>
      </ul>
    </li>
    <li>
      <div class="toggler" id="fridayList">Friday</div>
      <ul class="toggler-target">
        <li>
          <a class="btn btn-primary fw-light">Add Task</a>
          <a class="btn btn-danger fw-light">DeleteTask</a>
        </li>
      </ul>
    </li>
    <li>
      <div class="toggler">Saturday</div>
      <ul class="toggler-target" id="saturdayList">
        <li>
          <a class="btn btn-primary fw-light">Add Task</a>
          <a class="btn btn-danger fw-light">DeleteTask</a>
        </li>
      </ul>
    </li>
    <li>
      <div class="toggler">Sunday</div>
      <ul class="toggler-target" id="sundayList">
        <li>
          <a class="btn btn-primary fw-light">Add Task</a>
          <a class="btn btn-danger fw-light">DeleteTask</a>
        </li>
      </ul>
    </li>
  </ul>
  <script src="/js/script.js" defer charset="UTF-8"></script>
</div>

Answer №1

To effectively manage tasks, it is important to assign responsibilities.

By using this specific code snippet, you are essentially replacing all other existing code with the function addTask() {

document.getElmentById("todos").addEventListener("click",function(e) {
  const tgt = e.target;
  if (tgt.matches(".todo")) tgt.classList.toggle('active');
  else if (tgt.matches(".toggler")) {
     tgt.classList.toggle('active');
     tgt.nextElementSibling.classList.toggle('active');
  }
})

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

Postponed attaching event listeners to a Vue 3 instance within an iframe

Due to a specific requirement, I find myself in need of running a Vue instance inside an iframe. After some research and adjustments based on this thread from the Vue forum, I was able to achieve this goal while adapting the code for Vue 3 and removing unn ...

The routing feature functions properly on localhost but encounters issues on the live server

There seems to be an issue with this code. While it works perfectly on localhost, it doesn't function as expected on a live Apache server. I have already specified the homepage in the package JSON file and included an htaccess file. However, when acce ...

Removing page scrolling in Bootstrap 5: A step-by-step guide

I would like to ensure that only the card-body block is scrollable. Currently, the page does a bit of scrolling when the card-body block overflows (resulting in 2 scroll bars). The lorem text was added as an example of an overflow. The desired outcome is d ...

The MongoDB operator "$in" does not recognize the type array that currently exists in the field

When attempting to execute an aggregate query in mongodb, I encountered an issue with the "$in" operator stating that the field passed is not recognized as an array. Here is the aggregate query being used: [ { '$match': { 'isVis ...

The preflight request's response failed to meet the access control criteria due to the absence of the 'Access-Control-Allow-Origin' header

I encountered an issue while using ngResource to call a REST API hosted on Amazon Web Services: Upon making the request to , I received the following error message: "XMLHttpRequest cannot load. Response to preflight request doesn't pass access cont ...

Quickly align with vertices using threejs

As I delved into creating a snapping feature to align with my mesh vertices, I embarked on multiple trial-and-error solutions. One method involved introducing THREE.Sprite instances for each vertex in the scene and utilizing a rayCaster to determine if th ...

Is it possible for a function to locate the parent element of the anchor that initiated the function call?

My head is spinning just thinking about this question. There's an anchor tag that triggers a function: <a href="#" id="addPerson" onClick="addPerson(); return false;">Add a Guest</a> Here's the actual function being called: functi ...

Ways to display items at the bottom using flex

When you type a new message in a chat bot or messenger window, it typically appears at the bottom of the chat history while everything else moves up. This way, the user can always see the latest message without the chat window growing endlessly as older me ...

How can child components in ReactJS be conditionally rendered based on the status of userData loading?

It seems like there might be an issue with how we handle user login in our application. Whenever a user logs in, the redux state is updated with the server response. Many components rely on this logged-in status. We pass the currentUser object down to all ...

Switch up the image displayed when sharing content via buttons

Currently, I have implemented a custom sharing feature on my website using the code below: <div id="share_buttons"> <img src="images/facebook.png" onclick="popup('http://www.facebook.com/share.php?u=<?php echo $URL; ?>', &apos ...

Deliver an extensive JSON reply through a Node.js Express API

When dealing with a controller in a node/express API that generates large data sets for reports, reaching sizes as big as 20Mb per request, maintaining a positive user experience becomes essential. What strategies can be employed to efficiently handle suc ...

What is the method for adding up elements based on their identification numbers?

Is it possible to calculate the sum of multiple range sliders using their unique IDs? Multiplying each range slider value by the corresponding input. And finally, adding up all the multiplication results. $(document).ready(function() { $(".range") ...

Create a compressed package of a Vue project that can easily be inserted into a Blogger blog post as a single HTML file

Is there a way to package all the files related to a Vue.js project (HTML, JavaScript, CSS) into one single HTML file for easy deployment on a Blogger Blogspot post? In the past, a question similar to this was asked regarding bundling files into a single ...

Issues with the functionality of the bootstrap modal jQuery function in Firefox, causing problems with scrollbars and dynamic modal height adjustments

My newly launched website is built using bootstrap v3 and modals to showcase detailed information about each game server that is queried. Each modal provides insights into the current players on the server, their score, and play time. While implementing ...

Next.js React Server Components Problem - "ReactServerComponentsIssue"

Currently grappling with an issue while implementing React Server Components in my Next.js project. The specific error message I'm facing is as follows: Failed to compile ./src\app\components\projects\slider.js ReactServerComponent ...

Dynamic rows in an Angular 2 Material data table

I'm currently working on dynamically adding rows to an Angular 2 Data Table ( https://material.angular.io/components/table/overview) by utilizing a service called "ListService". This service provides me with the columns ("meta.attributes") to be displ ...

Ways to display an SVG spinner prior to a substantial UI refresh

I am currently facing an issue with updating 10 apexcharts bar charts simultaneously in a Vue app. When this process occurs, it takes approximately one second to load completely, and during that time, I would like to display an svg spinner. However, the co ...

Using Express.js to serve simple SVG files (Technique involving Cheerio.js)

My goal is to manipulate SVGs before sending them through Express.js. The code snippet I am using is as follows: app.get("/iconic/styles/:style/:base/:icon", function (req, res) { var style = req.params.style; var base = req.params.base; var i ...

Creating a Gulpfile.js that efficiently manages a multitude of files spread across various folders

For my ongoing WordPress projects, I am simultaneously working on themes and plugins. In my theme folder, I have a gulpfile.js that compiles .scss files into .css. I am considering creating a central "master" gulpfile in the root folder to compile .scss fi ...

Utilizing the protractor tool to navigate through menu options and access submenus efficiently

I am new to using Protractor and I'm struggling to write code that can select the menu, submenus, and click them within the div with id="navbar". Can someone please assist me with this issue? Unfortunately, I am facing difficulties posting the HTML co ...