I am writing simple JS app that shows weather. After first query variables like searchTerm or every variable from array are appends to the specific element. But after another query they are not override but added next to the previous one. How can i fix that? Should I use innerHTML or just refresh the page after another API call?
const form = document.querySelector('#searchForm');
const currentTemp = document.querySelector('#temp');
const feelingTemp = document.querySelector('#feelingTemp');
const button = document.querySelector('button');
const img = document.createElement('img');
const searchCity = document.querySelector('#searchingCity');
const sky = document.querySelector('#skyStatus');
const bg_image = document.querySelector('.left-container');
const moreInfo = document.querySelector('.right-container');
const getWeather = async () => {
try{
const searchTerm = form.elements.query.value
const res = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${searchTerm}&units=metric&appid=3861eeae573a8188b76a2d6c0ceccfb9`)
let getTemp = res.data.main.temp,
getFeelsTemp = res.data.main.feels_like,
getTempMin = res.data.main.temp_min,
getTempMax = res.data.main.temp_max,
getPressure = res.data.main.pressure,
getHumidity = res.data.main.humidity;
getSkyIcon = res.data.weather[0].main
searchCity.append(searchTerm)
form.elements.query.value = '';
return [getTemp, getFeelsTemp, getTempMin, getTempMax, getPressure, getHumidity, getSkyIcon]
} catch (e){
return "WEATHER SERVICE IS DOWN :("
}
}
const runApp = async () => {
form.addEventListener('submit', async function (e) {
e.preventDefault()
const [resTemp, resFeelsTemp, resTempMin, resTempMax, resPressure, resHumidity, resSkyIcon] = await getWeather()
// Głowny kontener informacyjny
currentTemp.append(`${Math.floor(resTemp)}°C`)
if(resSkyIcon === 'Clear'){
img.src = "./img/sun.png"
let finalImg = document.querySelector('#skyStatus')
finalImg.appendChild(img)
bg_image.style.backgroundImage = "url('img/sunny_bg.jpg')"
}else if(resSkyIcon === 'Clouds'){
img.src = "./img/cloud.png"
let finalImg = document.querySelector('#skyStatus')
finalImg.appendChild(img)
bg_image.style.backgroundImage = "url('img/cloud_bg.jpg')"
}else{
img.src = "./img/rain.png"
let finalImg = document.querySelector('#skyStatus')
finalImg.appendChild(img)
bg_image.style.backgroundImage = "url('img/rain_bg.jpg')"
}
// Right box
const array = [
`Feels temp ${Math.floor(resFeelsTemp)}°C`,
`Temp min ${Math.floor(resTempMin)}°C`,
`Temp max ${Math.floor(resTempMax)}°C`,
`Pressure ${resPressure}HPa`,
`Humidity ${resHumidity}%`
]
const ul = document.querySelector('ul');
array.forEach((value) =>{
const li = document.createElement('li');
li.innerText = value
ul.appendChild(li)
})
})
}
runApp();
<!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">
<title>WeatherApp - Rob</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="left-container">
<div class="form-container">
<form id="searchForm">
<input type="text" placeholder="Weather in" name="query" id="searchInput">
</form>
</div>
<div class="weather-output">
<h2 id="temp"></h2>
<h2 id="searchingCity"></h2>
<h2 id="skyStatus"></h2>
</div>
<div class="right-container">
<h2 id="right-header">Informacje dodatkowe</h2>
<div class="more-info-container">
<ul></ul>
</div>
</div>
</div>
<script src="./app2.js"></script>
</body>
</html>
You need to clear result that you get before
Just add:
searchCity.innerHTML = '';
...
currentTemp.innerHTML = '';
....
ul.innerHTML = '';
const form = document.querySelector('#searchForm');
const currentTemp = document.querySelector('#temp');
const feelingTemp = document.querySelector('#feelingTemp');
const button = document.querySelector('button');
const img = document.createElement('img');
const searchCity = document.querySelector('#searchingCity');
const sky = document.querySelector('#skyStatus');
const bg_image = document.querySelector('.left-container');
const moreInfo = document.querySelector('.right-container');
const getWeather = async () => {
try{
const searchTerm = form.elements.query.value
const res = await axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${searchTerm}&units=metric&appid=3861eeae573a8188b76a2d6c0ceccfb9`)
let getTemp = res.data.main.temp,
getFeelsTemp = res.data.main.feels_like,
getTempMin = res.data.main.temp_min,
getTempMax = res.data.main.temp_max,
getPressure = res.data.main.pressure,
getHumidity = res.data.main.humidity;
getSkyIcon = res.data.weather[0].main
searchCity.innerHTML = '';
searchCity.append(searchTerm)
form.elements.query.value = '';
return [getTemp, getFeelsTemp, getTempMin, getTempMax, getPressure, getHumidity, getSkyIcon]
} catch (e){
return "WEATHER SERVICE IS DOWN :("
}
}
const runApp = async () => {
form.addEventListener('submit', async function (e) {
e.preventDefault()
const [resTemp, resFeelsTemp, resTempMin, resTempMax, resPressure, resHumidity, resSkyIcon] = await getWeather()
// Głowny kontener informacyjny
currentTemp.innerHTML = '';
currentTemp.append(`${Math.floor(resTemp)}°C`)
if(resSkyIcon === 'Clear'){
img.src = "./img/sun.png"
let finalImg = document.querySelector('#skyStatus')
finalImg.appendChild(img)
bg_image.style.backgroundImage = "url('img/sunny_bg.jpg')"
}else if(resSkyIcon === 'Clouds'){
img.src = "./img/cloud.png"
let finalImg = document.querySelector('#skyStatus')
finalImg.appendChild(img)
bg_image.style.backgroundImage = "url('img/cloud_bg.jpg')"
}else{
img.src = "./img/rain.png"
let finalImg = document.querySelector('#skyStatus')
finalImg.appendChild(img)
bg_image.style.backgroundImage = "url('img/rain_bg.jpg')"
}
// Right box
const array = [
`Feels temp ${Math.floor(resFeelsTemp)}°C`,
`Temp min ${Math.floor(resTempMin)}°C`,
`Temp max ${Math.floor(resTempMax)}°C`,
`Pressure ${resPressure}HPa`,
`Humidity ${resHumidity}%`
]
const ul = document.querySelector('ul');
ul.innerHTML = '';
array.forEach((value) =>{
const li = document.createElement('li');
li.innerText = value
ul.appendChild(li)
})
})
}
runApp();
<!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">
<title>WeatherApp - Rob</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div class="left-container">
<div class="form-container">
<form id="searchForm">
<input type="text" placeholder="Weather in" name="query" id="searchInput">
</form>
</div>
<div class="weather-output">
<h2 id="temp"></h2>
<h2 id="searchingCity"></h2>
<h2 id="skyStatus"></h2>
</div>
<div class="right-container">
<h2 id="right-header">Informacje dodatkowe</h2>
<div class="more-info-container">
<ul></ul>
</div>
</div>
</div>
<script src="./app2.js"></script>
</body>
</html>
Related
I'm trying to display data from local storage to 2 HTML elements
that getting created after getting a click on the button function.
I can see in the "Application" tab "Local Storage" that the data is getting saved,
as you can see in the picture.
image here
I want to keep the HTML title and url getting saved even after I refresh the page.
Here is the HTML Code:
<!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">
<title>Work tracker</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="div-main">
<div class="div-box">
<h1 class="title-header">Work Tracker V1.00</h1>
<p>The app was built in order to save the progress of you'r work</p>
<label for="">Name</label>
<input type="text" class="input-title">
<label for="">Enter URL</label>
<input type="text" class="input-url"> </br>
<button class="btn-submit" onclick="createWork()">Submit work</button>
</div>
</div>
<div class="div-tree">
<h1>Tree Of Work</h1>
<div class="div-work">
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Here JavaScript Code
function createWork() {
let inputTitle = document.querySelector(".input-title").value;
let inputUrl = document.querySelector(".input-url").value;
let div = document.createElement('div');
let newTitle = document.createElement("h2");
let newUrl = document.createElement("h3");
div.className = "div-work";
document.body.appendChild(div);
div.appendChild(newTitle);
div.appendChild(newUrl);
newTitle.innerText = "Title: " + inputTitle;
newUrl.innerText = "URL: " + inputUrl;
// save data to local storage
localStorage.setItem('title', newTitle.innerText);
localStorage.setItem('url', newUrl.innerText);
if (localStorage["title"] && localStorage["url"]) {
let storedTitle = localStorage.getItem('title');
let storedUrl = localStorage.getItem('url');
console.log(storedTitle);
console.log(storedUrl);
}
};
You should run localStorage.getItem code snippet out of the createWork function.
if (localStorage["title"] && localStorage["url"]) {
let storedTitle = localStorage.getItem('title');
let storedUrl = localStorage.getItem('url');
console.log(storedTitle);
console.log(storedUrl);
let div = document.createElement('div');
let newTitle = document.createElement("h2");
let newUrl = document.createElement("h3");
div.className = "div-work";
document.body.appendChild(div);
div.appendChild(newTitle);
div.appendChild(newUrl);
newTitle.innerText = "Title: " + storedTitle;
newUrl.innerText = "URL: " + storedUrl;
}
function createWork() {
let inputTitle = document.querySelector(".input-title").value;
let inputUrl = document.querySelector(".input-url").value;
let div = document.createElement('div');
let newTitle = document.createElement("h2");
let newUrl = document.createElement("h3");
div.className = "div-work";
document.body.appendChild(div);
div.appendChild(newTitle);
div.appendChild(newUrl);
newTitle.innerText = "Title: " + inputTitle;
newUrl.innerText = "URL: " + inputUrl;
// save data to local storage
localStorage.setItem('title', newTitle.innerText);
localStorage.setItem('url', newUrl.innerText);
};
You were almost there
https://jsfiddle.net/mplungjan/e74fcon8/
Note I changed the inline click to an eventListener
window.addEventListener("DOMContentLoaded", () => {
const titleField = document.querySelector(".input-title");
const urlField = document.querySelector(".input-url")
const createWork = () => {
let inputTitle = titleField.value;
let inputUrl = urlField.value;
let div = document.createElement('div');
let newTitle = document.createElement("h2");
let newUrl = document.createElement("h3");
div.className = "div-work";
document.body.appendChild(div);
div.appendChild(newTitle);
div.appendChild(newUrl);
// save data to local storage
localStorage.setItem('title', inputTitle);
localStorage.setItem('url', inputUrl);
newTitle.innerText = "Title: " + inputTitle;
newUrl.innerText = "URL: " + inputUrl;
}
document.querySelector(".btn-submit").addEventListener("click",createWork)
if (localStorage.title && localStorage.url) {
let storedTitle = localStorage.getItem('title');
let storedUrl = localStorage.getItem('url');
titleField.value = storedTitle;
urlField.value = storedUrl;
createWork();
}
});
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");
};
So I'm using the PokeAPI to fetch the name of a Pokemon, then shuffling that name, and the user is supposed to guess what it is in the input. If they don't know then they can click the next button and it reshuffles a new mon. If they guess right they can press the same next button for a new mon. Each time they guess right the score increases by 1. That's working but I cant figure out why the out of/total games span isn't updating as well. Please excuse my terrible attempt at JS I'm very new if you can help me make my code look better that would be great.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<link rel="stylesheet" href="style.css" />
<title>Who's that Pkmn?</title>
</head>
<body>
<header>
<h1>Who's that Pokemon?!</h1>
</header>
<div id="jumble">?????</div>
<div class="container">
<input id="guess" type="text" placeholder="enter pkmn name" />
<button id="submit" class="btn" type="submit">go</button>
<button id="next" class="btn">next</button>
<p id="msg">unshuffle the letters</p>
</div>
<div id="scorekeepers">
<p>Score: <span id="score">0</span>
out of: <span id="gamesPlayed">0</span></p>
</div>
<script src="script.js"></script>
</body>
</html>
let jumbledName = document.querySelector("#jumble");
let guessInput = document.querySelector('#guess')
let submitButton = document.querySelector('#submit')
let nextButton=document.querySelector('#next')
let messageDisplay = document.querySelector('#msg')
let score = document.querySelector('#score')
let gamesPlayed = document.querySelector('#gamesPlayed')
score = 0;
gamesPlayed = 0;
let getPokemonName = function() {
fetch(`https://pokeapi.co/api/v2/pokemon/${Math.floor(Math.random()*151+1)}/`)
.then(function(response) {
return response.json();
})
.then(function(data) {
const pokeName = data.name;
const pokeNameJumbled = pokeName.shuffle();
displayInfomation(pokeName, pokeNameJumbled);
});
};
getPokemonName();
guessInput.value=''
// pokeNameJumbled=''
const displayInfomation = function(name, jumbledName) {
pokeName = name;
pokeNameJumbled = jumbledName;
jumble.textContent = jumbledName;
};
const displayMessage = function(message) {
document.querySelector("#msg").textContent = message;
};
const checkName = function () {
document.querySelector("#guess").textContent = guessInput;
const guess = document.querySelector("#guess").value.toLowerCase();
if (!guess) {
displayMessage("No guess entered!");
} else if (guess === pokeName) {
displayMessage(`Thats correct! It's ${pokeName}!`)
score++
document.querySelector("#score").textContent = score;
guessInput.value=''
} else if (guess != pokeName) {
displayMessage(`Wrong!`);
document.querySelector("#gamesPlayed").textContent = gamesPlayed;
}
};
submitButton.addEventListener('click', checkName)
nextButton.addEventListener('click',getPokemonName)
String.prototype.shuffle = function() {
var a = this.split(""),
n = a.length;
for (var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
return a.join("");
};
I'm trying to loop through the element that i create using DOM manipulation. it was successfully reflected in the html page but when i loop through in it using queryselector, its not looping. I also tried using getElementByClassName and still not looping.
here is the part of the code which I'm pointing out:
I also attached the whole javascript code with html for reference:
const selected = document.querySelector(".selected");
const optionsContainer = document.querySelector(".options-container");
window.addEventListener('DOMContentLoaded', () => {
createNewOption1();
createNewOption2();
});
const optionsList = document.querySelectorAll(".option");
selected.addEventListener("click", () => {
optionsContainer.classList.toggle("active");
});
optionsList.forEach(o => {
o.addEventListener("click", () => {
selected.innerHTML = o.querySelector("label").innerHTML;
optionsContainer.classList.remove("active");
});
});
const createNewOption1 = () => {
const div1 = document.createElement('div');
const input1 = document.createElement('input');
const label1 = document.createElement('label');
div1.className = 'option';
input1.type = 'radio';
input1.className = 'radio';
input1.name = 'category';
label1.htmlFor = 'Rejuvenating';
label1.innerHTML = 'Rejuvenating Set';
div1.appendChild(input1);
div1.appendChild(label1);
optionsContainer.appendChild(div1);
}
const createNewOption2 = () => {
const div2 = document.createElement('div');
const input2 = document.createElement('input');
const label2 = document.createElement('label');
div2.className = 'option';
input2.type = 'radio';
input2.className = 'radio';
input2.name = 'category';
label2.htmlFor = 'Maintenance';
label2.innerHTML = 'Maintenance Set';
div2.appendChild(input2);
div2.appendChild(label2);
optionsContainer.appendChild(div2);
}
<!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">
<title>Database Project</title>
<script src="https://kit.fontawesome.com/d6307e6979.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h2>Sales</h2>
<div class="select-box">
<div class="options-container">
</div>
<div class="selected">
<p>Select Item</p>
</div>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
You're creating the options in the DOMContentLoaded event listener. But you're calling querySelectorAll(".option") outside the listener, so the options don't exist yet. Move that code inside the listener.
const selected = document.querySelector(".selected");
const optionsContainer = document.querySelector(".options-container");
window.addEventListener('DOMContentLoaded', () => {
createNewOption1();
createNewOption2();
const optionsList = document.querySelectorAll(".option");
optionsList.forEach(o => {
o.addEventListener("click", () => {
selected.innerHTML = o.querySelector("label").innerHTML;
optionsContainer.classList.remove("active");
});
});
});
selected.addEventListener("click", () => {
optionsContainer.classList.toggle("active");
});
const createNewOption1 = () => {
const div1 = document.createElement('div');
const input1 = document.createElement('input');
const label1 = document.createElement('label');
div1.className = 'option';
input1.type = 'radio';
input1.className = 'radio';
input1.name = 'category';
label1.htmlFor = 'Rejuvenating';
label1.innerHTML = 'Rejuvenating Set';
div1.appendChild(input1);
div1.appendChild(label1);
optionsContainer.appendChild(div1);
}
const createNewOption2 = () => {
const div2 = document.createElement('div');
const input2 = document.createElement('input');
const label2 = document.createElement('label');
div2.className = 'option';
input2.type = 'radio';
input2.className = 'radio';
input2.name = 'category';
label2.htmlFor = 'Maintenance';
label2.innerHTML = 'Maintenance Set';
div2.appendChild(input2);
div2.appendChild(label2);
optionsContainer.appendChild(div2);
}
<!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">
<title>Database Project</title>
<script src="https://kit.fontawesome.com/d6307e6979.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<h2>Sales</h2>
<div class="select-box">
<div class="options-container">
</div>
<div class="selected">
<p>Select Item</p>
</div>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
Recently, I've started to learn html/css/javascript. Although I know some basic stuff I still struggle
with understanding some of the script parts.
I 've created a To Do List but its not finished yet. I'd like to add a button that deletes task but it does not work.
Can someone help me with delete button script part and explain in few words how it should work? This button is ruining everything, I am trying to fix it for five hours but it still doesn't work.
Here is my html code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="./style1.css" />
</head>
<body>
<div class="todo-cat">
<form class="todo-form" id="todoForm">
<div class="todo-form-row">
<label class="todo-form-label" for="todoMessage"
>Podaj treść zadania</label
>
<textarea
class="todo-form-message"
name="todoMessage"
id="todoMessage"
></textarea>
</div>
<div class="todo-form-row">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
</form>
<section class="todo-list-cat">
<header class="todo-list-header">
<h2 class="todo-list-title">Lista zadań</h2>
<form class="todo-list-search form">
<input type="search" id="todoSearch" class="todo-list-search" />
</form>
</header>
<div class="todo-list" id="todoList"></div>
</section>
</div>
And here is Script part :
<script>
let todoList = null;
let todoForm = null;
let todoSearch = null;
function addTask(text) {
//element todo
const todo = document.createElement("div");
todo.classList.add("todo-element");
//belka gorna
const todoBar = document.createElement("div");
todoBar.classList.add("todo-element-bar");
//data w belce
const todoDate = document.createElement("div");
todoDate.classList.add("todo-element-var");
const date = new Date();
const dateText = `${date.getDate()} - ${
date.getMonth() + 1
} - ${date.getFullYear()} godz.: ${date.getHours()}:${date.getMinutes()}`;
todoDate.innerText = dateText;
//przycisk usuwania
const todoDelete = document.createElement("button");
todoDelete.classList.add("todo-element-delete");
todoDelete.classList.add("button");
todoDelete.innerHTML = `<i class="fas fa-times-circle"></1>`;
//wrzucamy elementy do belki
todoBar.appendChild(todoDate);
todoBar.appendChild(todoDelete);
//element z tekstem
const todoText = document.createElement("div");
todoText.classList.add("todo-element-text");
todoText.innerHTML = text;
//łączymy całość
todo.appendChild(todoBar);
todo.appendChild(todoText);
//wrzucamy do listy
todoList.append(todo);
}
document.addEventListener("DOMContentLoaded", () => {
todoList = document.querySelector("#todoList");
todoForm = document.querySelector("#todoForm");
todoSearch = document.querySelector("todoSearch");
todoForm.addEventListener("submit", (e) => {
e.preventDefault();
const textarea = todoForm.querySelector("textarea");
if (textarea.value != "") {
addTask(textarea.value);
textarea.value = "";
}
});
});
</script>
<script
defer
src="https://use.fontawesome.com/releases/v5.0.2/js/all.js"
></script>
</body>
</html>
This should fix your problem. I've added an event listener to the delete button, then found the parent element on click and then removed it.
let todoList = null;
let todoForm = null;
let todoSearch = null;
function addTask(text) {
//element todo
const todo = document.createElement("div");
todo.classList.add("todo-element");
//belka gorna
const todoBar = document.createElement("div");
todoBar.classList.add("todo-element-bar");
//data w belce
const todoDate = document.createElement("div");
todoDate.classList.add("todo-element-var");
const date = new Date();
const dateText = `${date.getDate()} - ${
date.getMonth() + 1
} - ${date.getFullYear()} godz.: ${date.getHours()}:${date.getMinutes()}`;
todoDate.innerText = dateText;
//przycisk usuwania
const todoDelete = document.createElement("button");
todoDelete.classList.add("todo-element-delete");
todoDelete.classList.add("button");
todoDelete.innerHTML = `delete`;
todoDelete.addEventListener("click", function() {
this.closest(".todo-element").remove()
});
//wrzucamy elementy do belki
todoBar.appendChild(todoDate);
todoBar.appendChild(todoDelete);
//element z tekstem
const todoText = document.createElement("div");
todoText.classList.add("todo-element-text");
todoText.innerHTML = text;
//łączymy całość
todo.appendChild(todoBar);
todo.appendChild(todoText);
//wrzucamy do listy
todoList.append(todo);
}
document.addEventListener("DOMContentLoaded", () => {
todoList = document.querySelector("#todoList");
todoForm = document.querySelector("#todoForm");
todoSearch = document.querySelector("todoSearch");
todoForm.addEventListener("submit", (e) => {
e.preventDefault();
const textarea = todoForm.querySelector("textarea");
if (textarea.value != "") {
addTask(textarea.value);
textarea.value = "";
}
});
});
<div class="todo-cat">
<form class="todo-form" id="todoForm">
<div class="todo-form-row">
<label class="todo-form-label" for="todoMessage">Podaj treść zadania</label
>
<textarea
class="todo-form-message"
name="todoMessage"
id="todoMessage"
></textarea>
</div>
<div class="todo-form-row">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
</form>
<section class="todo-list-cat">
<header class="todo-list-header">
<h2 class="todo-list-title">Lista zadań</h2>
<form class="todo-list-search form">
<input type="search" id="todoSearch" class="todo-list-search" />
</form>
</header>
<div class="todo-list" id="todoList"></div>
</section>
</div>
Just add an onclick remove() event under your const todoDelete = document.createElement("button");
todoDelete.onclick = function () {
this.parentNode.parentNode.remove();
};
Now to explain how it works:
The button is 'this', the parentNode is the element above, the entire TODO item is two layers above and remove() will delete that one.
(This is your current structure, it is dependent on it)
<div class="todo-element">
<div class="todo-element-bar">
<div class="todo-element-var">3 - 9 - 2020 godz.: 14:28</div>
<button class="todo-element-delete button">BUTTON IS HERE</button>
</div>
<div class="todo-element-text">zrdz</div>
</div>
let todoList = null;
let todoForm = null;
let todoSearch = null;
function addTask(text) {
//element todo
const todo = document.createElement("div");
todo.classList.add("todo-element");
//belka gorna
const todoBar = document.createElement("div");
todoBar.classList.add("todo-element-bar");
//data w belce
const todoDate = document.createElement("div");
todoDate.classList.add("todo-element-var");
const date = new Date();
const dateText = `${date.getDate()} - ${
date.getMonth() + 1
} - ${date.getFullYear()} godz.: ${date.getHours()}:${date.getMinutes()}`;
todoDate.innerText = dateText;
//przycisk usuwania
const todoDelete = document.createElement("button");
todoDelete.onclick = function () {
this.parentNode.parentNode.remove();
};
todoDelete.classList.add("todo-element-delete");
todoDelete.classList.add("button");
todoDelete.innerHTML = `<i class="fas fa-times-circle"></1>`;
//wrzucamy elementy do belki
todoBar.appendChild(todoDate);
todoBar.appendChild(todoDelete);
//element z tekstem
const todoText = document.createElement("div");
todoText.classList.add("todo-element-text");
todoText.innerHTML = text;
//łączymy całość
todo.appendChild(todoBar);
todo.appendChild(todoText);
//wrzucamy do listy
todoList.append(todo);
}
document.addEventListener("DOMContentLoaded", () => {
todoList = document.querySelector("#todoList");
todoForm = document.querySelector("#todoForm");
todoSearch = document.querySelector("todoSearch");
todoForm.addEventListener("submit", (e) => {
e.preventDefault();
const textarea = todoForm.querySelector("textarea");
if (textarea.value != "") {
addTask(textarea.value);
textarea.value = "";
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="./style1.css" />
</head>
<body>
<div class="todo-cat">
<form class="todo-form" id="todoForm">
<div class="todo-form-row">
<label class="todo-form-label" for="todoMessage">Podaj treść zadania</label
>
<textarea
class="todo-form-message"
name="todoMessage"
id="todoMessage"
></textarea>
</div>
<div class="todo-form-row">
<button type="submit" class="button todo-form-button">Dodaj</button>
</div>
</form>
<section class="todo-list-cat">
<header class="todo-list-header">
<h2 class="todo-list-title">Lista zadań</h2>
<form class="todo-list-search form">
<input type="search" id="todoSearch" class="todo-list-search" />
</form>
</header>
<div class="todo-list" id="todoList"></div>
</section>
</div>
<script
defer
src="https://use.fontawesome.com/releases/v5.0.2/js/all.js"
></script>
</body>
</html>