I'm out over my skis as a newbie. The code block below isn't functional and I don't know how to do so because I can't find where it's wrong. What I'm trying to do: There is a list of data, with a NOTES field being able to be expanded and collapsed via the function notesField()--this toggles a class that transforms height of the block to 0. It works only when the page is first loaded.
Problem area: Then the user can add another block of data in the same format that is added to the page using insertAdjacentHTML in the renderLit function. However, once that data is added, the notesField function no longer functions correctly. I've verified that it's been called again.
I think it's because the DOM has been loaded, so that when a new block is called, the addeventlistener isn't attached to the new sections. I don't know why it stops working on existing html, though. I have seen some functionality about wrapping this in a timer like here Selecting an element by the class name after insertAdjacentHTML but I could not replicate it to work. I appreciate SO MUCH any tips you might be able to share.
notesField() { notesIcon.forEach((icon) => icon.addEventListener("click", function (icon) { //I know this is very ugly but it works and I couldn't figure out another way const selectedNotesField = this.parentElement.parentNode .nextElementSibling.lastElementChild; selectedNotesField.classList.toggle("collapsed"); this.classList.toggle("icon-selected"); }) ); } renderLit(formData) { let html = ` <div class="flex-container"> <i class="icon-notes icon-selected"></i> <span class="person">${person}</span> <span class="notes collapsed">${notes}</span> </div></div> `; correctElement.insertAdjacentHTML("afterend", html); this.notesField(); } } .collapsed { background: #fff; overflow: hidden; height: 0; transition: 0.5s; box-shadow: 1px 2px 4px rgba(0, 0, 0, 0.3); } .icon-selected { transform: rotate(180deg); transform-origin: center; transition: 0.2s; } <div class="flex-container"> <i class="icon-notes icon-selected"></i> <span class="person">John Henry</span> <span class="notes collapsed">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span> </div></div>
没有评论:
发表评论