Outputting An Object To A Page That Keeps Close Function
I posted this question before, among others. But it was suggested I need to ask a more specific or focused question. I am working on an output history log on a single page. And I w
Solution 1:
I created an example for you. Hopefully this helps you get going :) A couple things to note, I use a data attribute to store the index for the item in the array, so you can delete it when you click on the list item.
document.addEventListener('DOMContentLoaded', function(){
let nameEl = document.querySelector("#name");
let submitEl = document.querySelector("#submit-name");
let historyEl = document.querySelector(".history-list");
let historyList = [
{ name: 'Mitch'},
{ name: 'Max'},
{ name: 'Mike'},
];
functionaddToList(arr) {
// Clear up list and then update itwhile(historyEl.firstChild) {
historyEl.removeChild(historyEl.firstChild);
}
// Update the list with the historyListfor(let item in historyList) {
let name = historyList[item].name;
let listContent = document.createElement("li");
listContent.textContent = name;
// We will use the index to remove items from the list
listContent.setAttribute('data-value', item);
listContent.addEventListener("click", removeFromList)
historyEl.appendChild(listContent);
}
}
functionremoveFromList(index) {
// Takes the index of the object, and will later remove itconsole.log("Removed Item " + this.dataset.value);
historyList.splice(index, 1);
addToList(historyList);
}
addToList(historyList);
submitEl.addEventListener("click", function(event) {
if(nameEl.value) {
// Add the name to the start of the history list array.
historyList.unshift({ name: nameEl.value})
nameEl.value = '';
// Update the dom with the new arrayaddToList(historyList);
}
});
});
<labelfor="name">Type Name</label><inputtype="text"name="name"id="name"><buttonid="submit-name">Submit Name</button><ulclass="history-list"></ul>
Hopefully this gives you a good idea on how to get the task done and let me know if you have any questions :)
Solution 2:
Your boxes don't respond to the click event simply because your script crashes before the events even get attached to it. The following block right at the beginning:
document.getElementById("Add").onclick = function(e) {
convertOutput();
}
tries to add a click listener to the HTML element Add which does not exist. If you either remove the code block or add the appropriate element your boxes will have it's click functionality.
Post a Comment for "Outputting An Object To A Page That Keeps Close Function"