DEV Community

Dinesh G
Dinesh G

Posted on

My Java Full Stack Journey Learning in JavaScript

To-Do List in JavaScript

We’ll build a small app where you can:

Add tasks

.Display tasks in a list
.Delete tasks
.(Optional) Mark tasks as completed

eg code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }
        .delete-btn{
            background-color: red;
            color: white;
        }
        #todos li{
            display: flex;
            justify-content: space-between;
            background-color: rgb(201, 194, 194);
           margin-bottom: 20px;
        }
    </style>
</head>

<body>
    <h1>📝To-Do List</h1>
    <input type="text" id="user-input" placeholder="Enter task">
    <button id="btn">Add</button>

    <ul id="todos">


    </ul>

     <!-- <li></li> 
      <span>abcd</span> 
        <button>Delete</button> 

       <li><span>abcd</span> <button>Delete</button></li>  -->


    <script>
        const user_input = document.querySelector("#user-input");
        const btn = document.querySelector("#btn");
        const todos = document.querySelector("#todos");

        btn.addEventListener("click", () => {
            if (user_input.value == '') return;

            // create list item
               const li = document.createElement("li");

            //  create span tag and insert value
               const span = document.createElement("span");
               span.innerHTML = user_input.value;

            //    create delete button
               const deletebtn = document.createElement("button");
               deletebtn.innerHTML = "Delete";
               deletebtn.classList.add("delete-btn");


               li.appendChild(span);
               li.appendChild(deletebtn);

               todos.appendChild(li);

               deletebtn.addEventListener("click",()=>{
                li.remove();
               })   

            user_input.value = "";
        })
        todos.addEventListener("click",(event)=>{
           let li =  event.target.x1;
           li.remove();
        })


    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)