I'm creating a weather dashboard that updates every 5 seconds. I would like the user to be able to change the target city, and have the dashboard update with the new data.
Problem is every time they input a new city, the previous data stays and it seems to be looping through all the inputs the user has made so far.
I would like the data to be updated after the user inputs a new city, rather than added. This is my code:
window.onload = function() {
const api_key = "c7eedc2fa8594d69aa6122025212904";
const inputCity = document.getElementById("inputCity");
const getCity = document.querySelector("form");
getCity.addEventListener("submit", e => {
// Prevent the form from submission
e.preventDefault();
var inputVal = inputCity.value;
var api_url = "http://api.weatherapi.com/v1/forecast.json?key=" + api_key + "&q=" + inputVal + "&days=3&aqi=no&alerts=no";
// Get the dataset
function refreshData() {
fetch(api_url).then(response => {
response.json().then(json => {
var dataset = json;
var output = formatResponse(dataset);
})
// Catch error - for example, the user doesn't input a valid city / postcode / country
.catch(error => console.log("not ok")); // TO BE IMPROVED
})
}
refreshData(); // Display the dashboard immediately
setInterval(refreshData, 5000); // And then refresh the dashboard every X milliseconds
});
function formatResponse(dataset) {
console.log(dataset);
// Current temp
var currentTemp = [dataset.current.temp_c];
console.log(currentTemp);
document.getElementById("currentTempDsp").innerHTML = currentTemp + "°";
// Current state icon
var currentIcon = [dataset.current.condition.icon];
console.log(currentIcon);
document.getElementById("iconDsp").src = "http://" + currentIcon;
// Current state text
var currentText = [dataset.current.condition.text];
console.log(currentText[0]);
document.getElementById("currentStateDsp").innerHTML = currentText;
}
}
<form id="getCity" class="search">
<label id="labelCity">Search for a city...</label></br>
<input type="text" id="inputCity" class="inputCity" placeholder="Type city name here...">
<button id="submitCity" type="submit" class="submitCity"><i class="fas fa-search"></i>Submit</button>
</form>
<div class="state">
<h2 id="currentTempDsp"></h2>
<img id="iconDsp"/>
<span id="currentStateDsp"></span>
</div>
</div>
</div>
When you create an interval using setInterval() it continues to execute until the page is reloaded, navigated away from, or explicitly cleared using clearInterval(). Simply setting more intervals will not stop any previous ones from firing.
Use a globally-scoped variable to store the return value of setInterval() - check if it's set in the beginning of your submit event handler and clear it if it is.
A simplified example of how you could get this done:
const locations = [{
temp: 73,
conditions: 'Sunny'
}, {
temp: 22,
conditions: 'Mostly Cloudy'
}];
var currentInterval = null;
const updateTemp = locationData => {
document.querySelector(".number").innerText = locationData.temp;
document.querySelector(".conditions").innerText = locationData.conditions;
console.log(`updated interface with temperature (${locationData.temp}) and conditions (${locationData.conditions}) data`);
}
[...document.querySelectorAll('.add-location')].forEach(button => {
button.addEventListener('click', (e) => {
// clear the interval
if (currentInterval) {
clearInterval(currentInterval);
currentInterval = null;
console.log('cleared currentInterval');
}
updateTemp(locations[parseInt(e.srcElement.dataset.loc)]);
currentInterval = setInterval(function () {
updateTemp(locations[parseInt(e.srcElement.dataset.loc)]);
}, 2500);
});
});
* {
font-family: sans-serif;
}
.temp {
font-size: 2em;
}
.conditions {
font-style: italic;
}
<div class="temp">
<span class="number">--</span>
<span class="deg">°</span>
</div>
<div class="conditions">--</div>
<div>
<button class="add-location" data-loc="0">Add location 0</button>
<button class="add-location" data-loc="1">Add location 1</button>
</div>
Related
I am almost done with my to-do app, what is left is to do the local storage for the completed list and edited task.
The local storage I have done for when the task is added and removed. But I am not sure how to do the local storage for when the task is set to complete and when the task has been edited.
HTML
<div class="form">
<input class="user-input" type="text">
<input class="date" type="date">
<input class="time" type="time">
<button onclick="addTask()" class="add" id="add">+</button>
</div>
<div class="list"></div>
JS
//local storage key
const STORAGE_KEY = "tasks-storage-key";
// variables object
const el = {
form: document.querySelector(".form"),
input: document.querySelector(".user-input"),
list: document.querySelector(".list"),
date: document.querySelector(".date"),
time: document.querySelector(".time"),
};
const updateEl = {
formUpdate: document.querySelector(".form-update"),
inputUpdate: document.querySelector(".user-input"),
modal: document.querySelector(".modal"),
dateUpdate: document.querySelector(".date-update"),
timeUpdate: document.querySelector(".time-update"),
};
//Create ID
const createId = () =>
`${Math.floor(Math.random() * 10000)}${new Date().getTime()}`;
//variable of empty array that gets new task
let taskList = JSON.parse(window.localStorage.getItem(STORAGE_KEY) ?? "[]");
renderList();
function makeNewTask() {
const data = {
id: createId(),
taskNew: el.input.value,
taskDate: el.date.value,
taskTime: el.time.value,
};
return data;
}
function updateTask() {
const dataUpdate = {
id: createId(),
inputUpdate: updateEl.inputUpdate.value,
dateUpdate: updateEl.dateUpdate.value,
timeUpdate: updateEl.timeUpdate.value,
};
return dataUpdate;
}
function renderList() {
// This resets the list innerHTML to the new list
el.list.innerHTML = taskList.map(function (data) {
return `<div class="task">
<div class="task-content">
<div class="task" data-id="${data.id}">
<input class="new-task-created" value="${data.taskNew}" readonly></input>
<input class="due-date" type="date" value="${data.taskDate}" readonly></input>
<input class="due-time" type="time" value="${data.taskTime}" readonly></input>
</div>
<div class="action-buttons">
<button onclick="editItem(event)" class="edit" data-id="${data.id}">Edit</button>
<button onclick="deleteItem(event)" class="delete" data-id="${data.id}">Delete</button>
<button onclick="completeItem(event)" class="complete" data-id="${data.id}">Complete</button>
</div>`;
})
el.input.value = "";
}
//event listner that listens for add button.
function addTask() {
taskList.push(makeNewTask());
// store the list on localstorage because data changed
storeList();
// render list again because you've added a new entry
renderList();
}
//function that removes task from array with delete button.
function deleteItem(event) {
taskList.splice(taskList.indexOf(event.target.dataset.id), 1);
// store the list on localstorage because data changed
storeList();
// render list again because entry was removed
renderList();
}
//function that stores task list.
function storeList() {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(taskList));
}
//function that that edits tasks with date and time.
function editItem(event) {
const editEl = event.target.closest(".task");
let taskUpdate = editEl.querySelector(".new-task-created");
let dateUpdate = editEl.querySelector(".due-date");
let timeUpdate = editEl.querySelector(".due-time");
let editbtn = editEl.querySelector(".edit");
if (editbtn.innerHTML.toLowerCase() == "edit"){
taskUpdate.removeAttribute("readonly");
dateUpdate.removeAttribute("readonly");
timeUpdate.removeAttribute("readonly");
taskUpdate.focus();
editbtn.innerHTML = "Save";
}
else{
taskUpdate.setAttribute("readonly", "readonly");
dateUpdate.setAttribute("readonly", "readonly");
timeUpdate.setAttribute("readonly", "readonly");
editbtn.innerHTML = "Edit";
}
}
//function that that completes task.
function completeItem(event) {
const element = event.target.closest(".task-content");
let taskItem = element.querySelector(".new-task-created");
let dateItem = element.querySelector(".due-date");
let timeItem = element.querySelector(".due-time");
// style..
taskItem.style.textDecoration = "line-through";
dateItem.style.textDecoration = "line-through";
timeItem.style.textDecoration = "line-through";
}
I have added a screenshot of the section of the code I am focusing on, I just put the entire code so you can see the flow.
here in some changes in your js file look into it.
in editItem function on behalf of i we change value in taskList.
in completeItem function on behalf of i we add one more prop in object textDecoration: true and in renderList function we use prop to add style.
pass index i to each button action in function like editItem, deleteItem, completeItem .
//local storage key
const STORAGE_KEY = "tasks-storage-key";
// variables object
const el = {
form: document.querySelector(".form"),
input: document.querySelector(".user-input"),
list: document.querySelector(".list"),
date: document.querySelector(".date"),
time: document.querySelector(".time"),
};
const updateEl = {
formUpdate: document.querySelector(".form-update"),
inputUpdate: document.querySelector(".user-input"),
modal: document.querySelector(".modal"),
dateUpdate: document.querySelector(".date-update"),
timeUpdate: document.querySelector(".time-update"),
};
//Create ID
const createId = () =>
`${Math.floor(Math.random() * 10000)}${new Date().getTime()}`;
//variable of empty array that gets new task
let taskList = JSON.parse(window.localStorage.getItem(STORAGE_KEY) ?? "[]");
renderList();
function makeNewTask() {
const data = {
id: createId(),
taskNew: el.input.value,
taskDate: el.date.value,
taskTime: el.time.value,
};
return data;
}
function updateTask() {
const dataUpdate = {
id: createId(),
inputUpdate: updateEl.inputUpdate.value,
dateUpdate: updateEl.dateUpdate.value,
timeUpdate: updateEl.timeUpdate.value,
};
return dataUpdate;
}
function renderList() {
// This resets the list innerHTML to the new list
// <input class="new-task-created" value="${data.taskNew}" readonly style="text-decoration: 'line-through'"></input>
el.list.innerHTML = taskList.map(function (data, i) {
return `<div class="task">
<div class="task-content">
<div class="task" data-id="${data.id}" >
<input class="new-task-created" value="${data.taskNew}" readonly style="${data.textDecoration ? 'text-decoration: line-through': ''}"></input>
<input class="due-date" type="date" value="${data.taskDate}" readonly></input>
<input class="due-time" type="time" value="${data.taskTime}" readonly></input>
</div>
<div class="action-buttons">
<button onclick="editItem(event, ${i})" class="edit" data-id="${data.id}">Edit</button>
<button onclick="deleteItem(event, ${i})" class="delete" data-id="${data.id}">Delete</button>
<button onclick="completeItem(event, ${i})" class="complete" data-id="${data.id}">Complete</button>
</div>`;
})
el.input.value = "";
}
//event listner that listens for add button.
function addTask() {
taskList.push(makeNewTask());
// store the list on localstorage because data changed
storeList();
// render list again because you've added a new entry
renderList();
}
//function that removes task from array with delete button.
function deleteItem(event, i) {
taskList.splice(i, 1);
// store the list on localstorage because data changed
storeList();
// render list again because entry was removed
renderList();
}
//function that stores task list.
function storeList() {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(taskList));
}
//function that that edits tasks with date and time.
function editItem(event, i) {
const editEl = event.target.closest(".task");
let taskUpdate = editEl.querySelector(".new-task-created");
let dateUpdate = editEl.querySelector(".due-date");
let timeUpdate = editEl.querySelector(".due-time");
let editbtn = editEl.querySelector(".edit");
if (editbtn.innerHTML.toLowerCase() == "edit") {
taskUpdate.removeAttribute("readonly");
dateUpdate.removeAttribute("readonly");
timeUpdate.removeAttribute("readonly");
taskUpdate.focus();
editbtn.innerHTML = "Save";
}
else {
taskUpdate.setAttribute("readonly", "readonly");
dateUpdate.setAttribute("readonly", "readonly");
timeUpdate.setAttribute("readonly", "readonly");
editbtn.innerHTML = "Edit";
taskList[i] = {
id: taskList[i].id,
taskNew: taskUpdate.value,
taskDate: dateUpdate.value,
taskTime: timeUpdate.value
}
// store the list on localstorage because data changed
storeList();
// render list again because you've added a new entry
renderList();
}
}
//function that that completes task.
function completeItem(event, i) {
const element = event.target.closest(".task-content");
let taskItem = element.querySelector(".new-task-created");
let dateItem = element.querySelector(".due-date");
let timeItem = element.querySelector(".due-time");
// style..
taskItem.style.textDecoration = "line-through";
dateItem.style.textDecoration = "line-through";
timeItem.style.textDecoration = "line-through";
taskList[i] = {
...taskList[i],
textDecoration: true
}
console.log('taskList', taskList)
// store the list on localstorage because data changed
storeList();
// render list again because you've added a new entry
renderList();
}
For edited tasks I would first modify the updateTask() function so that it uses the same id as the originally created task:
//...
const taskData = {
id: createId(),
completed: false, // added
contents: el.input.value,
date: el.date.value,
time: el.time.value,
};
//...
You can modify the contents and the date/time to keep track of the last time it was modified. From there, you would do the simply call storeList() and renderList() to save to local storage and update the view.
For completed tasks I would either add a boolean property in the task data (something like completed) or a completion date (initially set to zero or null). From there you simply update and check for that value. And as for saving to local storage you would do the same: call storeList() and renderList().
I am trying to add a li element in the below div (Functionality is to upload an attachment)
See below pic 1
My JavaScript functionality of Submit button adds the Li in the div perfectly fine. But, when I refresh the page it's gone.
<input type="file" id="real-file" hidden="hidden" />
<button type="button" id="custom-button">CHOOSE A FILE</button>
<span id="custom-text">No file chosen, yet.</span>
<button type="button" id="submit-button" onclick="Submit()">Submit</button>
<div id="collapseThree">
</div>
<script>
const realFileBtn = document.getElementById("real-file");
const customBtn = document.getElementById("custom-button");
const customTxt = document.getElementById("custom-text");
const submitBtn = document.getElementById("submit-button");
const slides = [];
var str = '';
customBtn.addEventListener("click", function() {
realFileBtn.click();
});
window.addEventListener('load', (event) => {
console.log(slides)
console.log('The page has fully loaded yo');
// document.getElementById("collapseThree").innerHTML
});
/* window.onload = document.getElementById("slideContainer").innerHTML
*/
function Submit() {
console.log("going in");
document.getElementById("collapseThree").innerHTML += str
}
realFileBtn.addEventListener("change", function() {
if (realFileBtn.value) {
customTxt.innerHTML = realFileBtn.value.match(
/[\/\\]([\w\d\s\.\-\(\)]+)$/
)[1];
console.log(customTxt.innerHTML)
slides.push(customTxt.innerHTML);
slides.forEach(function(slide) {
str = '<li>' + slide + '</li>';
});
console.log(arr)
console.log(slides)
} else {
customTxt.innerHTML = "No file chosen, yet.";
}
});
</script>
You can use localStorage to save and read data. Simply call
function getSlides() {
var slidesJson = localStorage.getItem('slides') || '[]';
return JSON.parse(slidesJson);
}
to get all current slides and
function setSlides(slides) {
localStorage.setItem('slides', JSON.stringify(slides))
}
to save the current state of the array.
I'm trying to add links to my navbar for searches that users have made, as well as if the user favorites the link. What I'm currently trying to achieve is that if, if the "past searched" section already contains the current search, don't add the current search to avoid duplicates. I am using localStorage to store this data with a stringified array (alreadySearched) and check if this array includes the current search; my problem is that the function always returns false. The same thing happens for the favorites dropdown. What am I doing wrong?
Here's my code:
// primary movie information (API #1)
var getMovie = function(title) {
$("#result").addClass("hidden")
$("#main").removeClass("hidden");
$("#search-form").trigger("reset");
//format the OMDB api url
var apiUrl = `http://www.omdbapi.com/?t=${title}&plot=full&apikey=836f8b0`
//make a request to the url
fetch(apiUrl)
.then(function(response) {
// request was successful
if (response.ok) {
response.json().then(function(movieData) {
// console.log(movieData)
var movieTitle = movieData.Title
getMovieId(movieTitle);
getSoundTrack(movieTitle);
getTrailer(movieTitle);
var movieObj = {
title: movieTitle,
}
var pastSearches = loadPastSearches();
var alreadySearched = false
if (pastSearches) {
pastSearches.forEach(s => {
if (s.title === movieTitle) {
alreadySearched = true;
}
})
}
if (!alreadySearched) {
for (var item of pastSearches) {
let searchEl = document.createElement("a")
let pastSearchTitle = item.title
$(searchEl).text(pastSearchTitle)
$(searchEl).addClass("past-search-item");
$("#past-search-dropdown").append(searchEl)
$(searchEl).click(function(e) {
e.preventDefault();
let title = pastSearchTitle
getMovie(title)
getQuotes(title)
});
}
}
saveSearch(movieObj)
showMovie(movieData);
});
} else {
alert("Error: title not found!");
}
})
.catch(function(error) {
alert("Unable to connect to CineXScore app");
console.log(error)
});
};
// save past search
var saveSearch = function(movieObj) {
var pastSearches = loadPastSearches();
pastSearches.push(movieObj);
localStorage.setItem("movieObjects", JSON.stringify(pastSearches))
}
loadPastSearches = function() {
var pastSearches = JSON.parse(localStorage.getItem("movieObjects"));
if (!pastSearches || !Array.isArray(pastSearches)) {
var pastSearches = []
}
return pastSearches;
}
// dropdown favorite soundtrack buttons
var saveTrack = function(trackObj) {
var faveTracks = JSON.parse(localStorage.getItem("trackObjects"));
if (!faveTracks || !Array.isArray(faveTracks)) {
var faveTracks = []
}
var alreadySearched = false
if (faveTracks) {
faveTracks.forEach(t => {
if (t.name === trackObj.name) {
alreadySearched = true;
}
})
}
if (!alreadySearched) {
let trackEl = document.createElement("a")
$(trackEl).addClass("fave-track");
$(trackEl).text(trackObj.name);
$(trackEl).attr("href", trackObj.url);
$(trackEl).attr("target", "_blank")
$("#favorite-tracks-dropdown").append(trackEl)
}
faveTracks.push(trackObj);
localStorage.setItem("trackObjects", JSON.stringify(faveTracks))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Navigation Menu -->
<nav class="navbar navbar-default navbar-fixed-top">
<a id="logo" class="navbar-brand">CineXScore</a>
<div class="dropdown navbar-brand">Past Searches
<i class="fa fa-caret-down"></i>
<div id="past-search-dropdown" class="dropdown-content">
<a id="clear-searches">Clear</a>
</div>
</div>
<div class="dropdown navbar-brand">Favorite Tracks
<i class="fa fa-caret-down"></i>
<div id="favorite-tracks-dropdown" class="dropdown-content">
<a id="clear-favorites">Clear</a>
</div>
</div>
</nav>
This is a simple implementation that I think might help you.
async function fetchMovie(movieTitle) {
const apiUrl = `http://www.omdbapi.com/?t=${movieTitle}&plot=full&apikey=836f8b0`;
let res = await fetch(apiUrl);
res = await res.json();
const title = res.Title;
saveSearch(title); // Should only pass the string:title
}
fetchMovie('spiderman');
function saveSearch(title) {
if (!localStorage.getItem('movies')) localStorage.setItem('movies', ''); // Initialize the localStorage
// e.g: (In localStorage)
// Avenger,Spiderman,The Antman etc..
// return this string & convert into an array
let movies = localStorage
.getItem('movies')
.split(',')
.filter((n) => n);
// Check if the title is already exists
if (!movies.includes(title)) {
movies.push(title);
}
// Also store in localStorage as a string seperated by commas (,)
movies = movies.join(',');
localStorage.setItem('movies', movies);
}
I want to be able to update my JavaScript's object's properties(expense and income) so that it reflects on html when I click on the appropriate button.
My JS methods works as follows:
add income - which adds income found in the input (id = amountAdded)
add expense - which adds expense found in the input (id = amountAdded)
return an object that has balance, income and expense
reset values to 0 - this is done by accessing the JS object
However, when I press the appropriate button -- to add income, add expense or reset - nothing occurs. I added the code pen link below.
Account Balance Code Pen
let myAccount = {
name: 'John Doe',
income: 0,
expense: 0
}
let addIncome = function(){
amount = document.getElementById("amountAdded").value
myAccount.income+=amount
}
let addExpense = function(){
amount = document.getElementById("amountAdded").value
myAccount.expense+=amount
}
let resetAccount = function(){
myAccount.income=0
myAccount.expense=0
}
let getAccountSummary = function(){
//for ui logic
return {
balance: myAccount.income-myAccount.expense,
income: myAccount.income,
expense:myAccount.expense
}
}
let printAccountSummary = function(account){
//for developer
let accountSummary = getAccountSummary(account)
console.log(`
Balance: ${accountSummary.balance}
Income: ${accountSummary.income}
Expense: ${accountSummary.expense}
`)
}
// addExpense(account,100)
// addIncome(account,200)
// printAccountSummary(account)
//find app
var app = document.getElementById("root")
//make elements
var h1 = document.createElement("h1")
var text = document.createTextNode(`${myAccount.name}`)
var balance = document.createElement("p")
var balanceText = document.createTextNode(`Balance $${getAccountSummary(myAccount).balance}`)
var expense = document.createElement("p")
var expenseText = document.createTextNode(`Income $${getAccountSummary(myAccount).expense}`)
var income = document.createElement("p")
var incomeText = document.createTextNode(`Expense $${getAccountSummary(myAccount).income}`)
//assign elements
h1.appendChild(text)
balance.appendChild(balanceText)
income.appendChild(incomeText)
expense.appendChild(expenseText)
//append children
app.appendChild(h1)
app.appendChild(balance)
app.appendChild(income)
app.appendChild(expense)
<div class="container">
<!-- Use JavaScript to Populate Card -->
<div id="root" class="card">
</div>
<!-- Set Form Control to Add new Amounts -->
<div class="update">
<form>
<div class="input-group">
<input class="form-control" type="text" name="amountAdded" id="amountAdded" placeholder="Enter Amount"/>
<input type="button" class="btn btn-outline-secondary" value="Add Income" onclick="addIncome()"/>
<input type="button" class="btn btn-outline-secondary" value="Add Expense" onclick="addExpense()"/>
<input type="button" value="Reset" class="btn btn-outline-secondary" onclick="resetAccount()"/>
</div>
</form>
</div>
</div>
Simply you need to update the UI. Try this.
let myAccount = {
name: 'John Doe',
income: 0,
expense: 0
}
let addIncome = function(){
console.log('add income');
amount = document.getElementById("amountAdded").value
myAccount.income+=amount
updateUI()
}
let addExpense = function(){
amount = document.getElementById("amountAdded").value
myAccount.expense+=amount
}
let resetAccount = function(){
myAccount.income=0
myAccount.expense=0
}
let getAccountSummary = function(){
//for ui logic
return {
balance: myAccount.income-myAccount.expense,
income: myAccount.income,
expense:myAccount.expense
}
}
let printAccountSummary = function(account){
//for developer
let accountSummary = getAccountSummary(account)
console.log(`
Balance: ${accountSummary.balance}
Income: ${accountSummary.income}
Expense: ${accountSummary.expense}
`)
}
// addExpense(account,100)
// addIncome(account,200)
// printAccountSummary(account)
let updateUI = function() {
//find app
var app = document.getElementById("root")
app.innerHTML = '';
//make elements
var h1 = document.createElement("h1")
var text = document.createTextNode(`${myAccount.name}`)
var balance = document.createElement("p")
var balanceText = document.createTextNode(`Balance $${getAccountSummary(myAccount).balance}`)
var expense = document.createElement("p")
var expenseText = document.createTextNode(`Income $${getAccountSummary(myAccount).expense}`)
var income = document.createElement("p")
var incomeText = document.createTextNode(`Expense $${getAccountSummary(myAccount).income}`)
//assign elements
h1.appendChild(text)
balance.appendChild(balanceText)
income.appendChild(incomeText)
expense.appendChild(expenseText)
//append children
app.appendChild(h1)
app.appendChild(balance)
app.appendChild(income)
app.appendChild(expense)
}
updateUI()
Also, note that updating UI directly with JavaScript is not nice. If your project is too big, it will be chaos in the future
you need update the values for the p tags u are using to show the income, balance and expense p tags. u can do this by adding a classname to them and when u click add income or add expense, get the elements by their classname and update their values
I have a simple text input where users type anything and after sumbitting text appear on a page and stays there, which I done with localStorage, but after refreshing the page only last typed input is showing, Ill post my code to be more specific:
HTML:
<body>
<input id="NewPostField" type="text" value="">
<button onclick="myFunction()">Post</button>
<div id="Posts"></div>
</body>
JavaScript:
function myFunction() {
var NewPostField =
document.getElementById("NewPostField");
var newPost = document.createElement("p");
localStorage.setItem('text',
NewPostField.value);
newPost.innerHTML = NewPostField.value;
var Posts = document.getElementById("Posts");
Posts.appendChild(newPost);
}
(function() {
const previousText = localStorage.getItem('text');
if (previousText) {
var NewPostField = document.getElementById("NewPostField");
NewPostField.value = previousText;
myFunction();
}
})();
Any help will be great!
It seems that your code is only storing the last value posted.
To store more than one post, one idea is to stringify an array of values to store in localStorage.
Then, parse that stringified value back into an array as needed.
Here's an example:
function getExistingPosts() {
// fetch existing data from localStorage
var existingPosts = localStorage.getItem('text');
try {
// try to parse it
existingPosts = JSON.parse(existingPosts);
} catch (e) {}
// return parsed data or an empty array
return existingPosts || [];
}
function displayPost(post) {
// display a post
var new_post = document.createElement("p");
new_post.innerHTML = post;
posts.appendChild(new_post);
}
function displayExistingPosts() {
// display all existing posts
var existingPosts = getExistingPosts();
posts.innerHTML = '';
inputPost.value = '';
if (existingPosts.length > 0) {
existingPosts.forEach(function(v) {
displayPost(v);
});
inputPost.value = existingPosts.slice(-1)[0];
}
}
function addPost(post) {
// add a post
var existing = getExistingPosts();
existing.push(post);
localStorage.setItem('text', JSON.stringify(existing));
displayPost(post);
}
function clearPosts() {
// clear all posts
localStorage.removeItem('text');
displayExistingPosts();
}
var posts = document.getElementById("posts");
var inputPost = document.getElementById("input_post");
var btnPost = document.getElementById('btn_post');
var btnClear = document.getElementById('btn_clear');
btnPost.addEventListener('click', function() {
addPost(inputPost.value)
});
btnClear.addEventListener('click', clearPosts);
displayExistingPosts();
<input id="input_post" type="text" value="">
<button type="button" id="btn_post">Post</button>
<button type="button" id="btn_clear">Clear</button>
<div id="posts"></div>
Since localStorage isn't supported in StackSnippets, here's a JSFiddle to help demonstrate.