Last active
July 1, 2019 21:59
-
-
Save armaandh/0519c4837338771fc4bcb8f3f6564d49 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var button = document.getElementById("enter"); | |
| var input = document.getElementById("userinput"); | |
| var ul = document.querySelector("ul"); | |
| function inputLength() { | |
| return input.value.length; | |
| } | |
| function createListElement() { | |
| var li = document.createElement("li"); // <li></li> | |
| li.appendChild(document.createTextNode(input.value)); // <li>test</li> | |
| var button = document.createElement("button"); // <button></button> | |
| button.classList.add("deleteButton"); // <button class="deleteButton"></button> | |
| button.innerText = "Delete"; // <button class="deleteButton">Delete</button> | |
| li.appendChild(button); // <li>test <button class="deleteButton">Delete</button> </li> | |
| ul.appendChild(li); // <ul> <li>test <button class="deleteButton">Delete</button> </li> </ul> | |
| addEventListeners(li); // call function to add an event listener ONLY to THIS <li> (passed as an argument) | |
| input.value = ""; | |
| } | |
| function addListAfterClick() { | |
| if (inputLength() > 0) { | |
| createListElement(); | |
| } | |
| } | |
| function addListAfterKeypress(event) { | |
| if (inputLength() > 0 && event.keyCode === 13) { | |
| createListElement(); | |
| } | |
| } | |
| button.addEventListener("click", addListAfterClick); | |
| input.addEventListener("keypress", addListAfterKeypress); | |
| function toggleHandler(event) { | |
| event.target.classList.toggle("done"); | |
| } | |
| function removeTodoItemHandler(event) { | |
| var li = event.target.parentElement; | |
| li.parentElement.removeChild(li); | |
| } | |
| function addEventListeners(liArg) { | |
| if (liArg != undefined) { | |
| liArg.addEventListener("click", toggleHandler); | |
| liArg.firstElementChild.addEventListener("click", removeTodoItemHandler); | |
| } else { | |
| Array.from(ul.children).forEach(function(li) { | |
| li.addEventListener("click", toggleHandler); | |
| li.firstElementChild.addEventListener("click", removeTodoItemHandler); | |
| }); | |
| } | |
| } | |
| addEventListeners(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment