Errror when adding event listener to the status btns of a LS todo project

the html code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.min.css"
        />
        <style>
            * {
                box-sizing: border-box;
                padding: 0;
                margin: 0;
            }

            body {
                display: flex;
                justify-content: center;
                align-items: center;
                background: #032a7e;
                width: 100%;
                min-height: 100vh;
                font-family: Arial, Helvetica, sans-serif;
            }

            #main {
                width: 350px;
                max-width: 95%;
                display: grid;
                grid-template-rows: repeat(3, auto);
                gap: 3rem;
            }

            h2 {
                margin-top: 30px;
                text-align: center;
                line-height: 1.8;
                color: white;
            }

            .todo {
                /* background: #030e27; */
                padding: 10px 20px;
                border-bottom: 2px solid #888;
                color: #fff;
                display: flex;
                justify-content: space-between;
                align-items: center;
                height: 45px;
                font-size: 0.875rem;
                transition: all 0.3s cubic-bezier(1, 0, 0, 1);
            }

            .todo:first-child {
                border-top-left-radius: 5px;
                border-top-right-radius: 5px;
            }

            .todo:last-child {
                border-bottom-left-radius: 5px;
                border-bottom-right-radius: 5px;
                border-bottom: 0;
            }

            #info-input {
                display: flex;
                justify-content: space-between;
            }

            input {
                width: calc(100% - 50px);
                padding: 10px 20px;
                height: 40px;
                background: #222;
                border: 0;
                border-radius: 5px;
                color: #fff;

                &:focus {
                    outline: none;
                }

                &::placeholder {
                    color: #666;
                }
            }

            .adder-button {
                height: 40px;
                width: 40px;
                display: flex;
                justify-content: center;
                align-items: center;
                border: 0;
                border-radius: 5px;
                background: rgb(63, 138, 243);
                color: #fff;
                font-size: 1.25rem;
                margin-bottom: 3rem;
                cursor: pointer;
            }

            .bi-trash,
            .bi-x-circle,
            .bi-check-circle {
                transition: 0.2s ease-in-out color;
            }

            .bi-trash:hover,
            .bi-x-circle:hover,
            .bi-check-circle:hover {
                color: orange;
                cursor: pointer;
            }

            .icons-container {
                display: flex;
                justify-content: flex-end;
                align-items: center;
                gap: 10px;
            }
        </style>
        <title>Todos Mananger | ❤️</title>
    </head>
    <body>
        <div id="main">
            <h2>
                Things <span style="color: royalblue">you</span> want to do...
            </h2>
            <div class="todos-container"></div>
            <div id="info-input">
                <input type="text" placeholder="Add New Task" maxlength="20" minlength="1"/>
                <button class="adder-button"><i class="bi bi-plus"></i></button>
            </div>
        </div>
        <script src="js/app.js"></script>
    </body>
</html>

and the javascript code:

function _q(p) {
    return document.querySelector(p);
}
function _qa(p) {
    return document.querySelectorAll(p);
}
const todosList = _q(".todos-container");
const info = _q("input");
const adder = _q(".adder-button");
const iconTrash = `<i class="bi bi-trash"></i>`;
let i;
let trashIcons;
let todos;
let todoStatus;
let newObj;
let todoToRemove;
let todoToModify;
let statusBtns;
let alreadyExists;


// function to order the ids of the todo objects in the localstorage when a todo is eliminated
function todosUpdater() {
    todosSelector();
    i = 0;
    todos.forEach((todo) => {
        todo.id = i;
        i++;
    });
    localStorage.setItem("todos", JSON.stringify(todos));
}

// function to save "todos" array(from localstorage) in todos variable
function todosSelector() {
    todos = JSON.parse(localStorage.getItem("todos"));
}

// function to select trash icons
function trashIconSelector() {
    trashIcons = _qa(".bi-trash");
}

//function to set an event listener for each trash icon
function trashIconHandler() {
    trashIcons.forEach((trashIcon) => {
        trashIcon.addEventListener("click", (e) => {
            todosSelector();
            todoToRemove = todos.findIndex((todo) => {
                return todo.id == e.target.parentElement.dataset.id;
            });
            todos.splice(todoToRemove, 1);
            localStorage.setItem("todos", JSON.stringify(todos));
            e.target.parentElement.parentElement.remove();
            todosUpdater();
        });
    });
}


// function to set event listener for status buttons and to program them
// the error happens when calling this function back***********
function statusBtnsEventSetter() {
    statusBtns = _qa("i:last-child");
    statusBtns.forEach((statusBtn) => {
        statusBtn.addEventListener("click", (e) => {
            todosSelector();
            todoToModify = todos.findIndex((todo) => {
                return (
                    todo.id == e.target.parentElement.parentElement.dataset.id
                );
            });
            todoStatus = todos[todoToModify].completed == true ? true : false;
            if (todoStatus) {
                todos[todoToModify].completed = false;
                e.target.parentElement.parentElement.style.background =
                    "#041a48";
                e.target.className = "bi-check-circle";
            } else {
                todos[todoToModify].completed = true;
                e.target.parentElement.parentElement.style.background =
                    "#057719";
                e.target.className = "bi-x-circle";
            }
            localStorage.setItem("todos", JSON.stringify(todos));
        });
    });
}

// function to add localstorage todos to DOM
function initializer() {
    info.value = "";
    if (JSON.parse(localStorage.getItem("todos")) == null) {
        localStorage.setItem("todos", JSON.stringify([]));
    } else {
        todosSelector();
        i = 0;
        todos.forEach((todo) => {
            todoStatus = todo.completed == true ? true : false;
            if (!todoStatus) {
                todosList.innerHTML +=
                    `<div data-id="` +
                    i +
                    `" class="todo" style="background: #041a48;">` +
                    todo.name +
                    `<div class="icons-container">` +
                    iconTrash +
                    `<i class="bi bi-check-circle"></i>` +
                    `</div>` +
                    `</div>`;
            } else {
                todosList.innerHTML +=
                    `<div data-id="` +
                    i +
                    `" class="todo" style="background: #057719;">` +
                    todo.name +
                    `<div class="icons-container">` +
                    iconTrash +
                    `<i class="bi bi-x-circle"></i>` +
                    `</div>` +
                    `</div>`;
            }
            i++;
        });
        statusBtnsEventSetter();
        trashIconSelector();
        trashIconHandler();
    }
}

// event listeners:

window.addEventListener("load", initializer);

adder.addEventListener("click", () => {
    todosSelector();
    alreadyExists = todos.some((todo) => {
        return todo.name == info.value.trim();
    });
    if (
        info.value.trim().length > 1 &&
        info.value.trim().length <= 20 &&
        !alreadyExists
    ) {
        (function (txt) {
            txt = info.value.trim();
            i = todos.length;
            newObj = { id: i, name: txt, completed: false };
            todos.push(newObj);
            localStorage.setItem("todos", JSON.stringify(todos));
            todosList.innerHTML +=
                `<div data-id="` +
                i +
                `" class="todo" style="background: #041a48;">` +
                txt +
                `<div class="icons-container">` +
                iconTrash +
                `<i class="bi bi-check-circle"></i>` +
                `</div>` +
                `</div>`;
            // priority may need to be changed
            statusBtnsEventSetter();
            trashIconSelector();
            trashIconHandler();
        }());
    }
});

it’s a todo project which has to be saved in localStoraege in which you could add todos, remove them, and change their status(whether they’re completed or not).

the code works fine before you try to add a new todo. I mean suppose you want to work with your current todos; It’s just FINE but as soon as you try to add a new todo, you face an error telling that the “todoToModify” variable is -1 which means the findIndex method fails to return the appropriate value for todoToModify.
-the todo gets added to the DOM but when you refresh, the initializer loads the todos in a wrong way(check what i said with multiple todos added, removed or having the status changed).

please run and review the code to see what happens.

I can’t think of anything else working wrong. The main problem is the statusBtnsEventSetter function.

at first the status changer was in a way that you could change it by simply clicking on the todo box itself. I added the status buttons because I wondered if the error was because of parenting when adding event listeners. But it didn’t help.

10

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

Errror when adding event listener to the status btns of a LS todo project

the html code:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link
            rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.min.css"
        />
        <style>
            * {
                box-sizing: border-box;
                padding: 0;
                margin: 0;
            }

            body {
                display: flex;
                justify-content: center;
                align-items: center;
                background: #032a7e;
                width: 100%;
                min-height: 100vh;
                font-family: Arial, Helvetica, sans-serif;
            }

            #main {
                width: 350px;
                max-width: 95%;
                display: grid;
                grid-template-rows: repeat(3, auto);
                gap: 3rem;
            }

            h2 {
                margin-top: 30px;
                text-align: center;
                line-height: 1.8;
                color: white;
            }

            .todo {
                /* background: #030e27; */
                padding: 10px 20px;
                border-bottom: 2px solid #888;
                color: #fff;
                display: flex;
                justify-content: space-between;
                align-items: center;
                height: 45px;
                font-size: 0.875rem;
                transition: all 0.3s cubic-bezier(1, 0, 0, 1);
            }

            .todo:first-child {
                border-top-left-radius: 5px;
                border-top-right-radius: 5px;
            }

            .todo:last-child {
                border-bottom-left-radius: 5px;
                border-bottom-right-radius: 5px;
                border-bottom: 0;
            }

            #info-input {
                display: flex;
                justify-content: space-between;
            }

            input {
                width: calc(100% - 50px);
                padding: 10px 20px;
                height: 40px;
                background: #222;
                border: 0;
                border-radius: 5px;
                color: #fff;

                &:focus {
                    outline: none;
                }

                &::placeholder {
                    color: #666;
                }
            }

            .adder-button {
                height: 40px;
                width: 40px;
                display: flex;
                justify-content: center;
                align-items: center;
                border: 0;
                border-radius: 5px;
                background: rgb(63, 138, 243);
                color: #fff;
                font-size: 1.25rem;
                margin-bottom: 3rem;
                cursor: pointer;
            }

            .bi-trash,
            .bi-x-circle,
            .bi-check-circle {
                transition: 0.2s ease-in-out color;
            }

            .bi-trash:hover,
            .bi-x-circle:hover,
            .bi-check-circle:hover {
                color: orange;
                cursor: pointer;
            }

            .icons-container {
                display: flex;
                justify-content: flex-end;
                align-items: center;
                gap: 10px;
            }
        </style>
        <title>Todos Mananger | ❤️</title>
    </head>
    <body>
        <div id="main">
            <h2>
                Things <span style="color: royalblue">you</span> want to do...
            </h2>
            <div class="todos-container"></div>
            <div id="info-input">
                <input type="text" placeholder="Add New Task" maxlength="20" minlength="1"/>
                <button class="adder-button"><i class="bi bi-plus"></i></button>
            </div>
        </div>
        <script src="js/app.js"></script>
    </body>
</html>

and the javascript code:

function _q(p) {
    return document.querySelector(p);
}
function _qa(p) {
    return document.querySelectorAll(p);
}
const todosList = _q(".todos-container");
const info = _q("input");
const adder = _q(".adder-button");
const iconTrash = `<i class="bi bi-trash"></i>`;
let i;
let trashIcons;
let todos;
let todoStatus;
let newObj;
let todoToRemove;
let todoToModify;
let statusBtns;
let alreadyExists;


// function to order the ids of the todo objects in the localstorage when a todo is eliminated
function todosUpdater() {
    todosSelector();
    i = 0;
    todos.forEach((todo) => {
        todo.id = i;
        i++;
    });
    localStorage.setItem("todos", JSON.stringify(todos));
}

// function to save "todos" array(from localstorage) in todos variable
function todosSelector() {
    todos = JSON.parse(localStorage.getItem("todos"));
}

// function to select trash icons
function trashIconSelector() {
    trashIcons = _qa(".bi-trash");
}

//function to set an event listener for each trash icon
function trashIconHandler() {
    trashIcons.forEach((trashIcon) => {
        trashIcon.addEventListener("click", (e) => {
            todosSelector();
            todoToRemove = todos.findIndex((todo) => {
                return todo.id == e.target.parentElement.dataset.id;
            });
            todos.splice(todoToRemove, 1);
            localStorage.setItem("todos", JSON.stringify(todos));
            e.target.parentElement.parentElement.remove();
            todosUpdater();
        });
    });
}


// function to set event listener for status buttons and to program them
// the error happens when calling this function back***********
function statusBtnsEventSetter() {
    statusBtns = _qa("i:last-child");
    statusBtns.forEach((statusBtn) => {
        statusBtn.addEventListener("click", (e) => {
            todosSelector();
            todoToModify = todos.findIndex((todo) => {
                return (
                    todo.id == e.target.parentElement.parentElement.dataset.id
                );
            });
            todoStatus = todos[todoToModify].completed == true ? true : false;
            if (todoStatus) {
                todos[todoToModify].completed = false;
                e.target.parentElement.parentElement.style.background =
                    "#041a48";
                e.target.className = "bi-check-circle";
            } else {
                todos[todoToModify].completed = true;
                e.target.parentElement.parentElement.style.background =
                    "#057719";
                e.target.className = "bi-x-circle";
            }
            localStorage.setItem("todos", JSON.stringify(todos));
        });
    });
}

// function to add localstorage todos to DOM
function initializer() {
    info.value = "";
    if (JSON.parse(localStorage.getItem("todos")) == null) {
        localStorage.setItem("todos", JSON.stringify([]));
    } else {
        todosSelector();
        i = 0;
        todos.forEach((todo) => {
            todoStatus = todo.completed == true ? true : false;
            if (!todoStatus) {
                todosList.innerHTML +=
                    `<div data-id="` +
                    i +
                    `" class="todo" style="background: #041a48;">` +
                    todo.name +
                    `<div class="icons-container">` +
                    iconTrash +
                    `<i class="bi bi-check-circle"></i>` +
                    `</div>` +
                    `</div>`;
            } else {
                todosList.innerHTML +=
                    `<div data-id="` +
                    i +
                    `" class="todo" style="background: #057719;">` +
                    todo.name +
                    `<div class="icons-container">` +
                    iconTrash +
                    `<i class="bi bi-x-circle"></i>` +
                    `</div>` +
                    `</div>`;
            }
            i++;
        });
        statusBtnsEventSetter();
        trashIconSelector();
        trashIconHandler();
    }
}

// event listeners:

window.addEventListener("load", initializer);

adder.addEventListener("click", () => {
    todosSelector();
    alreadyExists = todos.some((todo) => {
        return todo.name == info.value.trim();
    });
    if (
        info.value.trim().length > 1 &&
        info.value.trim().length <= 20 &&
        !alreadyExists
    ) {
        (function (txt) {
            txt = info.value.trim();
            i = todos.length;
            newObj = { id: i, name: txt, completed: false };
            todos.push(newObj);
            localStorage.setItem("todos", JSON.stringify(todos));
            todosList.innerHTML +=
                `<div data-id="` +
                i +
                `" class="todo" style="background: #041a48;">` +
                txt +
                `<div class="icons-container">` +
                iconTrash +
                `<i class="bi bi-check-circle"></i>` +
                `</div>` +
                `</div>`;
            // priority may need to be changed
            statusBtnsEventSetter();
            trashIconSelector();
            trashIconHandler();
        }());
    }
});

it’s a todo project which has to be saved in localStoraege in which you could add todos, remove them, and change their status(whether they’re completed or not).

the code works fine before you try to add a new todo. I mean suppose you want to work with your current todos; It’s just FINE but as soon as you try to add a new todo, you face an error telling that the “todoToModify” variable is -1 which means the findIndex method fails to return the appropriate value for todoToModify.
-the todo gets added to the DOM but when you refresh, the initializer loads the todos in a wrong way(check what i said with multiple todos added, removed or having the status changed).

please run and review the code to see what happens.

I can’t think of anything else working wrong. The main problem is the statusBtnsEventSetter function.

at first the status changer was in a way that you could change it by simply clicking on the todo box itself. I added the status buttons because I wondered if the error was because of parenting when adding event listeners. But it didn’t help.

10

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật