You need to add event listener again when you update the DOM
After you call document.body.appendChild(newNotesEl);
, add event listener on edit
class in newNotesEl
. -
document.body.appendChild(newNotesEl);
newNotesEl.querySelector('.edit').addEventListener("click", () => {
console.log('Helll');
main.classList.toggle("hidden");
textArea.classList.toggle("hidden");
});
You can extract out the event code into a function, so you need not repeat code.
const notesEl = document.querySelector(".notes");
const editBtn = document.querySelector(".edit");
const deleteBtn = document.querySelector(".delete");
const addNoteBtn = document.querySelector(".add-note");
const main = notesEl.querySelector(".main");
const textArea = notesEl.querySelector("textarea");
editBtn.addEventListener("click", () => {
console.log('Helll');
main.classList.toggle("hidden");
textArea.classList.toggle("hidden");
});
textArea.addEventListener("input", (e) => {
const {
value
} = e.target;
main.innerHTML = marked(value);
});
addNoteBtn.addEventListener("click", () => {
const newNotesEl = document.createElement("div");
newNotesEl.classList.add("notes");
newNotesEl.innerHTML = `
<div class="notes-tools">
<button class="edit"><i class="fas fa-edit"></i></button>
<button class="delete"><i class="fas fa-trash-alt"></i></button>
</div>
<div class="main hidden"></div>
<textarea></textarea>
`;
document.body.appendChild(newNotesEl);
newNotesEl.querySelector('.edit').addEventListener("click", () => {
console.log('Helll');
main.classList.toggle("hidden");
textArea.classList.toggle("hidden");
});
});
body {
background-color: #7bdaf3;
display: flex;
flex-wrap: wrap;
font-family: "Poppins", sans-serif;
min-height: 100vh;
margin: 0;
}
.add-note {
background-color: #9ec862;
color: #fff;
position: fixed;
top: 1rem;
right: 1rem;
border: none;
padding: 0.5rem;
border-radius: 4px;
font-size: 1.2rem;
}
.add-icon {
margin-left: 4px;
}
.notes {
background-color: #fff;
width: 380px;
height: 400px;
margin: 60px 20px;
}
.notes .notes-tools {
background-color: #9ec862;
display: flex;
justify-content: flex-end;
padding: 0.5rem;
}
.notes .notes-tools button {
background-color: transparent;
color: #fff;
border: none;
font-size: 1rem;
margin-left: 0.5rem;
}
.notes .main {
height: 100%;
width: 100%;
}
.notes textarea {
outline: none;
font-family: inherit;
border: none;
height: 100%;
width: 100%;
}
.notes .hidden {
display: none;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/marked/1.2.7/marked.min.js"></script>
<body>
<button class="add-note">Add Note<i class="far fa-plus-square add-icon"></i></button>
<div class="notes">
<div class="notes-tools">
<button class="edit"><i class="fas fa-edit"></i></button>
<button class="delete"><i class="fas fa-trash-alt"></i></button>
</div>
<div class="main hidden"></div>
<textarea></textarea>
</div>
</body>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…