Interview can ask you to create a To-do List with the help on Html and Javascript only without use of React. In this case the knowledge of Event bubbling, Event delegation is must.
Event Bubbling: Event bubbles from child to parent.
Event Capturing: Event Capturing from parent to child.
document.addEventlistener("click",handleClick,true);
If we pass true in this event capturing will happen. and false will cause the bubbling.
Now, Where this find useful:
Suppose you have 3 div nested one another making child div , parent div, grand parent div.
If we attach a console.log() on every div. So in event bubbling we will get the child console.log first and then parent and so on. vice versa with event capturing.
Now, what is event delegation:
So, Instead of attaching individual event listener to a list of item, we attach a common event listener to the list and handle every list item click.
Advantages of Event Delegation:
Code reuse.
Code Simplification.
Disadvantages:
Some event doen't get propogated
Ex: focus, blur
Example :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To Do List</title>
</head>
<body>
<h1>To Do List</h1>
<input id="inputField" type="text" placeholder="Add Item" />
<button id="submit">Submit</button>
<ul id="listItem"></ul>
<script src="./ToDoList.js"></script>
</body>
</html>
let submitBtn = document.getElementById("submit");
let list = document.getElementById("listItem");
function handleSubmitBtnClick() {
let inputText = document.getElementById("inputField");
let inputValue = inputText.value.trim();
// Handle empty input value
if (inputValue === "") return;
// Create Node
let li = document.createElement("li");
const text = document.createElement("p");
text.className = "todo-text";
text.textContent = inputValue;
let completeBtn = document.createElement("button");
completeBtn.classList = "complete-btn";
completeBtn.textContent = "Complete";
let deleteBtn = document.createElement("button");
deleteBtn.classList = "delete-btn";
deleteBtn.textContent = "Delete";
li.append(text, completeBtn, deleteBtn);
list.append(li);
inputText.value = "";
inputText.focus();
return;
}
function handleListClick(e) {
const target = e.target;
if (target.classList.contains("delete-btn")) {
target.closest("li").remove();
}
if (target.classList.contains("complete-btn")) {
const todoText = target.closest("li").querySelector(".todo-text");
todoText.style.textDecoration =
todoText.style.textDecoration === "line-through"
? "none"
: "line-through";
}
}
submitBtn.addEventListener("click", handleSubmitBtnClick);
list.addEventListener("click", handleListClick);
Top comments (0)