How to interact with an several appended childs - javascript

i am creating a todo list as a beginner exercise to train my JS skills but i hit a wall (again). As you can see in my code, i can create tasks that need doing and to each task i appended 2 buttons. Now i want both buttons to do the same thing (remove the task). I would like to create a addEventListener to those buttons but since i created them through JS and not HTML i don't now how to access them or their behavior (i don't know how to get their ID or if they even have one). So my question is this: how can i access those buttons through JavaScript? Thanks.
let b1 = document.getElementById('addItem');
let d1 = document.getElementById('resetList');
let content = document.getElementById('listItem').value;
let Liste = document.getElementById('laListe');
var addTask = function() {
var text = document.getElementById('listItem').value;
var li = document.createElement('li');
var buttons = document.createElement('button');
buttons.innerHTML = "X";
var buttons2 = document.createElement('button');
buttons2.innerHTML = "Done";
li.innerHTML = text;
li.append(document.createTextNode(" "));
document.getElementById('laListe').appendChild(li).appendChild(buttons);
li.append(document.createTextNode(" "));
li.append(buttons2);
}
document.getElementById('addItem').onclick = function(event) {
event.preventDefault()
};
b1.addEventListener('click', function() {
addTask();
});
d1.addEventListener('click', function() {
document.getElementById('laListe').innerText = " ";
});
document.getElementById('resetList').onclick = function(event) {
event.preventDefault()
};
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="Todo.css">
<title>ToDo App</title>
<script src='todo.js' defer></script>
</head>
<body>
<h1>To-Do List</h1>
<form id="Listcreator" name="itemAdd">
<input id="listItem" type="text">
<button id="addItem" type="submit"> Ajouter </button>
<button id="resetList" type="submit"> Tout Enlever</button>
</form>
<ul id="laListe"> </ul>
</body>

var buttons = document.createElement('button');
buttons.innerHTML = "X";
buttons.addEventListener("click", function(){
this.parentNode.remove();
});
var buttons2 = document.createElement('button');
buttons2.innerHTML = "Done";
buttons2.addEventListener("click", function(){
this.parentNode.remove();
});

You can add an event listener to your buttons when they are created.
https://jsfiddle.net/cnsxaL3b/
After adding event listeners, your code should look like below:
let b1 = document.getElementById('addItem');
let d1 = document.getElementById('resetList');
let content = document.getElementById('listItem').value;
let Liste = document.getElementById('laListe');
var addTask = function() {
var text = document.getElementById('listItem').value;
var li = document.createElement('li');
var buttons = document.createElement('button');
buttons.innerHTML = "X";
var buttons2 = document.createElement('button');
// Event listener for first button
buttons.addEventListener('click', function() {
alert('clicked button1');
});
// Event listener for first button
buttons2.addEventListener('click', function() {
alert('clicked button2');
});
buttons2.innerHTML = "Done";
li.innerHTML = text;
li.append(document.createTextNode(" "));
document.getElementById('laListe').appendChild(li).appendChild(buttons);
li.append(document.createTextNode(" "));
li.append(buttons2);
}
document.getElementById('addItem').onclick = function(event) {
event.preventDefault()
};
b1.addEventListener('click', function() {
addTask();
});
d1.addEventListener('click', function() {
document.getElementById('laListe').innerText = " ";
});
document.getElementById('resetList').onclick = function(event) {
event.preventDefault()
};

Related

How to reload current page without losing added list items?

I'm creating something similar to a to-do-list project, but whenever I refresh the page I lose all the added items, I've tried using:
`
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list");
};
`
but still it doesn't work, I may have used it in the wrong place or wrong way. any help please?
here is my full code:
HTML:
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css" />
<title>To Do List</title>
</head>
<body>
<section class="section-center">
<form class="todolist-form">
<h3>To Do List!</h3>
<div class="input-button">
<input type="text" id="items-input" placeholder="e.g. eggs" />
<input
type="button"
class="submit-btn"
onclick="addItems()"
value="Submit"
/>
</div>
<div class="added-items">
<ul id="faves"></ul>
</div>
</form>
</section>
<script src="main.js"></script>
</body>
</html>
`
Javascript:
`
function addItems() {
var li = document.createElement("LI");
li.setAttribute("id", "listItem");
var input = document.getElementById("items-input");
li.innerHTML = input.value;
input.value = "";
document.getElementById("faves").appendChild(li);
var deleteBtn = document.createElement("button");
deleteBtn.classList.add("delete-btn");
deleteBtn.innerHTML = "Delete";
deleteBtn.type = "button";
document.getElementById("faves").appendChild(deleteBtn);
var hrzBreak = document.createElement("br");
document.getElementById("faves").appendChild(hrzBreak);
/*********/
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list");
};
}
`
What am I doing wrong? I've included jQuery's CDN too, but still it doesn't work.
var texts = [];
function addItems() {
var input = document.getElementById("items-input");
createElement(input.value)
input.value = "";
}
function createElement(value) {
var li = document.createElement("LI");
li.setAttribute("id", "listItem");
li.innerHTML = value;
document.getElementById("faves").appendChild(li);
var deleteBtn = document.createElement("button");
deleteBtn.classList.add("delete-btn");
deleteBtn.innerHTML = "Delete";
deleteBtn.type = "button";
document.getElementById("faves").appendChild(deleteBtn);
var hrzBreak = document.createElement("br");
document.getElementById("faves").appendChild(hrzBreak);
texts.push(value)
}
window.onbeforeunload = function () {
// Store text array in storage
localStorage.setItem("list", JSON.stringify(texts));
};
window.onload = function () {
// get list grom storage
var list = localStorage.getItem("list");
if (list !== null) {
list = JSON.parse(list)
for (let index = 0; index < list.length; index++) {
const element = list[index];
// create your dom element
createElement(element)
}
}
};
Using an Array to manage the data flow. This will do the job but still a mess.
Try adding event listeners once and outside of your function
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list")
};
function addItems() {
...
}
Assuming that $("#listItem").val() will return the data you want, place below block outsite of the addItems() function
window.onbeforeunload = function () {
localStorage.setItem("list", $("#listItem").val());
};
window.onload = function () {
var name = localStorage.getItem("list");
if (name !== null) $("#listItem").val("list");
};

JavaScript keyup event bug

I have annoying bug in my code. On event key Enter, the user is not able to add item unless the first item is added manually(on click Add). How can I fix this? I appreciate any help or hints how to solve it! Thank you!
function selectColorStatus(event){
let target = event.target;
target.classList.toggle('todoTextSelected');
}
function createToDoItem(userInputValue){
// To-Do Item Container
let todoItem = document.createElement("div");
todoItem.classList.add("row", "flx");
todoItem.onclick = selectColorStatus;
// Inner Text
let todoText = document.createElement('div');
todoText.classList.add('grow');
todoText.innerText = userInputValue;
// Date
let CreateDate = document.createElement('div');
CreateDate.classList.add('date');
let date = new Date();
year = date.getFullYear();
month = date.getMonth();
day = date.getDay();
CreateDate.innerText = 'Created at ' + year + '-' + month + '-'+ day;
// Delete Button
let deleteBtn = document.createElement('div');
deleteBtn.classList.add('btnDelete');
deleteBtn.innerText = 'X';
deleteBtn.onclick = function(){
todoItem.remove();
}
todoItem.appendChild(todoText);
todoItem.appendChild(CreateDate)
todoItem.appendChild(deleteBtn);
let todoItemsContainer = document.getElementById('todoItemsContainer');
todoItemsContainer.appendChild(todoItem);
}
// Item Entry and Validation
function ToDoItemHandler(){
let userInput = document.getElementById('toDoEntry');
let userInputValue = userInput.value;
if(userInputValue == ''){
alert('Entry can not be empty!')
}else{
userInput.onkeydown = pressFunc;
function pressFunc(e){
if(e.key == 'Enter' || e.key == 13){
createToDoItem(userInputValue);
userInput.value = '';
}
}
createToDoItem(userInputValue);
userInput.value = '';
}
}
// Clear List
let btnDeleteItem = document.getElementById('btnDeleteItem');
btnDeleteItem.onclick = function (){
// or document.getElementById('todoItemsContainer').innerHTML = ''
const items = document.querySelectorAll('.row')
items.forEach(el => {
el.remove()
})
}
// Add Item Button
let btnAddItem = document.getElementById('btnAddItem');
btnAddItem.onclick = ToDoItemHandler;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href = './style/style.css' rel='stylesheet'>
<title>To-Do-List</title>
</head>
<body>
<div id = 'container'>
<div id="toDoHeader">
<h1>To-Do List</h1>
<div id = 'toDoContent'>
<input type = 'text' id = 'toDoEntry' name = 'toDoEntry' placeholder = 'Add item here'>
<button type = 'button' id = 'btnAddItem' name = 'addToDoList'>Add</button>
<button type = 'button' id = 'btnDeleteItem' name = 'deleteList'>Delete All</button>
</div>
</div>
<div id="todoItemsContainer">
</div>
</div>
<script src = './js/app.js'></script>
</body>
</html>
Your event handler for onKeyDown will be created after you click btnAddItem.
you have to put this " userInput.onkeydown = pressFunc; " outside the function. so the event handler registered without click the btnAddItem first. do it like you register btnAddItem event handler below // Add Item Button

Trying to delete todo list but not working

var inputItem = document.getElementById("inputItem");
function addItem(list, input) {
var inputItem = this.inputItem;
var list = document.getElementById(list);
var listItem = document.createElement("li");
var deleteButton = document.createElement("button");
deleteButton.innerText = "delete";
deleteButton.addEventListener("click", function() {
//console.log("Delete");
//var ul=document.getElementById("list");
var listItem = list.children;
for (var i=0; i < listItem.length; i++) {
while(listItem[i] && listItem[i].children[0].checked) {
ul.removeChild(listItem[i]);
}
}
});
var checkBox = document.createElement("input");
checkBox.type = 'checkbox';
var label = document.createElement("label");
var labelText = document.createElement("span");
labelText.innerText = input.value;
label.appendChild(checkBox);
label.appendChild(labelText);
listItem.appendChild(label);
listItem.appendChild(deleteButton);
list.appendChild(listItem);
inputItem.focus();
inputItem.select();
return false;
}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>To-Do List</title>
</head>
<body>
<h1>To-Do List</h1>
<form onsubmit="return addItem('list', this.inputItem)">
<input type="text" id="inputItem">
<input type="submit">
</form>
<ul id="list">
</ul>
</body>
</html>
So first of all, there are a few little mistakes in the code:
var list = document.getElementById(list); - You're using the list as the parameter, not a string.
while(listItem[i] && listItem[i].children[0].checked) { - Not sure why you're using while here instead of if.
ul.removeChild(listItem[i]); - ul is commented a few lines above.
Besides these, the delete does not work because of the following line:
if(listItem[i] && listItem[i].children[0].checked) {
If you analyze the DOM, the list item contains a <label></label> that contains the input, which means children[0] is not what you expect it to be.
Therefore, fixing the issues mentioned above and replacing the check in the delete callback function with
if(listItem[i] && listItem[i].getElementsByTagName('input')[0].checked) {
list.removeChild(listItem[i]);
}
should be your fix.

Add and Delete text using 2 buttons in javascript (conditions : use div id 'divResult' , console log.)

I want to make a webpage with 2 buttons (Add, Delete). Conditions are using div id divResult , console log and after removing that div has to stay. It works almost correct, just last step (remove alinea) doesn`t work. Can you help me , how can i fix it? :-)
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>2 buttons</title>
<script >
var index = 1;
window.onload = function () {
document.getElementById('Btn1').onclick = function () {
var newElement = document.createElement('div');
newElement.id = 'div' + index++;
var node = document.getElementById('txtElement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
};
document.getElementById('Btn2').onclick = function () {
var oldDiv = document.getElementById('txtElement')
var alinea = oldDiv.querySelectorAll('p:last-child')[0];
console.log(alinea + ' wordt verwijderd...');
oldDiv.removeChild(alinea);
console.log('verwijderd!');
};
};
</script>
</head>
<body>
<p>Type your text in the text box and click on Button</p>
<input type="text" id="txtElement">
<button id="Btn1">Add</button>
<button id="Btn2">Delete</button>
<div id="divResult"></div>
<div id="oldDiv"></div>
</body>
</html>
I've tried a few things, moved stuff around. I think it's doing what you want now.
var index = 1;
window.onload = function () {
document.getElementById('Btn1').onclick = function () {
var newElement = document.createElement('div');
newElement.id = 'div' + index++;
var node = document.getElementById('txtElement').value;
var newNode = document.createTextNode(node);
newElement.appendChild(newNode);
console.log(newElement);
document.getElementById('divResult').appendChild(newElement);
};
document.getElementById('Btn2').onclick = function () {
var oldDiv = document.getElementById('txtElement');
var divResult = document.getElementById('divResult');
var alinea = divResult.querySelectorAll('div:last-child')[0];
console.log(alinea + ' wordt verwijderd...');
alinea.remove();
// divResult.removeChild(alinea);
console.log('verwijderd!');
};
};
<p>Type your text in the text box and click on Button</p>
<input type="text" id="txtElement">
<button id="Btn1">Add</button>
<button id="Btn2">Delete</button>
<div id="divResult"></div>
<div id="oldDiv"></div>
If I understand you correctly, change the following section:
document.getElementById('Btn2').onclick = function () {
var alinea = document.getElementById('div'+ --index);
console.log(alinea.innerHTML + ' wordt verwijderd...');
alinea.remove(alinea);
console.log('verwijderd!');
};

Wrapping a .addEventListener in a div tag

I am compleatly new to js and I need help using html inbetween the lines.
i have this event:
eventSource.addEventListener('Uptime', function(e) {
var parsedData = JSON.parse(e.data);
var tempSpan = document.getElementById("uptime");
var tsSpan = document.getElementById("tstamp");
tempSpan.innerHTML = parsedData.data;
tempSpan.style.fontSize = "28px";
tsSpan.innerHTML = "At timestamp " + parsedData.published_at;
tsSpan.style.fontSize = "9px";
}, false);
it listens for events from my Spark Core en updates my website with the status.
What i want is the status being showed inside my div.
<div id="on"> </div>
Is this possible?
Complete code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Spark.aspx.cs" Inherits="Spark" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="/Content/bootstrap.css" rel="stylesheet" type="text/css" />
</head>
<body>
<span id="uptime"></span><br>
<span id="tstamp"></span>
<br><br>
<button onclick="start()">Connect</button>
<script type="text/javascript">
function start() {
document.getElementById("uptime").innerHTML = "Waiting for data...";
var deviceID = "";
var accessToken = "";
var eventSource = new EventSource("https://api.spark.io/v1/devices/" + deviceID + "/events/?access_token=" + accessToken);
eventSource.addEventListener('open', function(e) {
console.log("Opened!"); },false);
eventSource.addEventListener('error', function(e) {
console.log("Errored!"); },false);
<!--THIS IS THE METHOD I WANT INSIDE THE DIV-->
eventSource.addEventListener('Uptime', function(e) {
var parsedData = JSON.parse(e.data);
var tempSpan = document.getElementById("uptime");
var tsSpan = document.getElementById("tstamp");
tempSpan.innerHTML = parsedData.data;
tempSpan.style.fontSize = "28px";
tsSpan.innerHTML = "At timestamp " + parsedData.published_at;
tsSpan.style.fontSize = "9px";
var div = document.createElement("div")
div.innerHTML = parsedData.status;
document.body.appendChild(div);
document.getElementById("on").innerHTML = parsedData.status;
}, false);
}
</script>
Heres a screenshot. http://imgur.com/sX2ES0P
To be more spesific, I'm trying to show the text "Borte" in the div
At the end of your event, just do (assuming status is a value inside parsedData):
document.getElementById("on").innerHTML = parsedData.status;
That's assuming you have the div on the page, if you don't then you'd have to create it first:
var div = document.createElement("div")
div.innerHTML = parsedData.status;
document.body.appendChild(div);

Categories

Resources