how to store my data in local storage as object from what I've got - javascript

Two buttons counting and storing data in local storage, just trying to make it store as obj in local storage, but I'm a newbie and couldn't make it work can some1 explain how to do it from what I've got? thank you! don't know if I can just add this here or need to do it from scratch?
const wellbtn = document.querySelector('.wellbtn');
const unwellbtn = document.querySelector('.unwellbtn');
const moodwell = document.querySelector('.moodwell')
const moodunwell = document.querySelector('.moodunwell')
let wellcounter = localStorage.getItem('wellcounter');
let unwellcounter = localStorage.getItem('unwellcounter');
moodwell.innerText = `You felt well ${wellcounter} times`;
moodunwell.innerText = `You felt unwell ${unwellcounter} times`;
const addWellCounter = (() => {
moodwell.innerText = `You felt well ${++wellcounter} times`
localStorage.setItem('wellcounter', wellcounter.toString());
})
const addUnwellCounter = (() => {
moodunwell.innerText = `You felt unwell ${++unwellcounter} times`
localStorage.setItem('unwellcounter', unwellcounter.toString());
})
wellbtn.addEventListener('click', () => {
addWellCounter();
})
unwellbtn.addEventListener('click', () => {
addUnwellCounter();
});
<!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>My title</title>
</head>
<body>
<h1>How do you feel ?</h1>
<button class="wellbtn">Well</button>
<button class="unwellbtn">Unwell</button>
<p class="moodwell">You felt well 0 times</p>
<p class="moodunwell">You felt unwell 0 times</p>
</body>
</html>

Related

Openweather API linking the searchbar to the actual city chosen from the hard coding part

I am currently working on a weather app using Openweather API, and I'm having a little strugle on creating the function that in the moment that a city is written in the search bar and the button search is pressed, I want the h1 with the class "chosen-location" textcontent to change into the input from the search bar, this thing should happen by changing the value of the variable city into the content from the searchbar. That's how I would do it if I would have some more expierence, but I don't know how to really write all this stuff.
const apikey = `45d2b1974108dfa1128c4ce9991a1f56`;
let city = "Constanta";
let search = document.querySelector('.searchbar');
let button = document.querySelector('.btn');
window.addEventListener('load', ()=>{
let long;
let lat;
let temperatureDescription = document.querySelector('.temperature-description');
let temperatureDegree = document.querySelector('.degree');
let locationTimezone = document.querySelector('.location-timezone');
let icon = document.querySelector('.icon');
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(position => {
long = position.coords.longitude;
lat = position.coords.latitude;
// what i've done here takes your coordinates and puts them to the variables mentioned
const api = `https://api.openweathermap.org/data/2.5/weather?q=${city}&APPID=${apikey}&units=metric`;
fetch(api)
.then(respones => {
return respones.json();
})
.then(data =>{
console.log(data);
const {temp} = data.main;
const {main} = data.weather[0];
const {country} = data.sys;
// set DOM elements from the API
temperatureDegree.textContent = temp;
temperatureDescription.textContent = main;
locationTimezone.textContent = country;
if(temperatureDescription.textContent === 'Mist'){
document.querySelector('.icon').src='http://openweathermap.org/img/wn/50d#2x.png';
}if(temperatureDescription.textContent === 'Clear Sky'){
document.querySelector('.icon').src='http://openweathermap.org/img/wn/01d#2x.png';
}if(temperatureDescription.textContent === 'Clouds'){
document.querySelector('.icon').src='http://openweathermap.org/img/wn/03d#2x.png';
}if(temperatureDescription.textContent === 'Rain'){
document.querySelector('.icon').src='http://openweathermap.org/img/wn/10d#2x.png';
}if(temperatureDescription.textContent === 'Thunderstorm'){
document.querySelector('.icon').src='http://openweathermap.org/img/wn/11d#2x.png';
}if(temperatureDescription.textContent === 'Snow'){
document.querySelector('.icon').src='http://openweathermap.org/img/wn/13d#2x.png';
}
console.log(temperatureDescription.textContent);
});});
}
});
<!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">
<link rel="stylesheet" href="styles.css">
<title> Weather app </title>
</head>
<body>
<div class="location">
<h1 class="location-timezone">Timezone</h1>
<h1 class="chosen-location">Constanta</h1>
<img class= "icon" src="http://openweathermap.org/img/wn/01d#2x.png" alt="weather">
</div>
<div class="search"><input type="text" placeholder="Ex:Chicago" class="searchbar"></div> <button class="btn">Search</button>
<div class="temperature">
<div class="degree-section">
<h2 class="degree">34</h2>
<span> Celsius</span>
</div>
<div class="temperature-description">It's frkin cold</div>
</div>
<script type ="module" src="script.js"></script>
</body>
</html>

JS extract button text content on click

Im making a simple rock paper scissors game with html and js. I have got the computer to randomly choose one of the three options, but now I'm having issues with getting the users input by extracting the text content straight from the button. I know that I can get the value by having an event listener for all three button separately but just thought that it would be much better if I could have one event listener for all three.
Right now I am able to read the text content of the first button which is rock, but i'm not sure how to go about doing the same for the others on click.
My code so far:
let optionsArray = ["rock", "paper", "scissors"];
const getComputerChoice = () => {
let randomNumber = Math.floor(Math.random() * optionsArray.length);
return optionsArray[randomNumber];
};
const getPlayerChoice = () => {
const choice = document.querySelector("button");
let playerChoice = choice.textContent;
console.log(playerChoice);
};
getPlayerChoice();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>ROCK PAPER SCISSORS</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="" />
</head>
<body>
<button>rock</button>
<button>paper</button>
<button>scissors</button>
<script src="script.js" async defer></script>
</body>
</html>
Any help would be greatly appreciated.
You'll need one or more event listeners, which can either be on each button or on a parent element. You can use event.target.closest("button") to determine which button was clicked using event delegation.
const rpsOptions = ["rock", "paper", "scissors"];
const computerChoice = () =>
rpsOptions[~~(Math.random()*rpsOptions.length)];
const optionsEl = document.querySelector(".rps-options");
optionsEl.addEventListener("click", event => {
const btn = event.target.closest("button");
if (!btn || !optionsEl.contains(btn)) {
return;
}
console.log(
`you chose ${btn.textContent}, ` +
`computer chose ${computerChoice()}`
);
});
<div class="rps-options">
<button>rock</button>
<button>paper</button>
<button>scissors</button>
</div>

How to loop pokemons out from the PokeAPI?

Hi I am in the process of fetching data down from the pokeapi, I can loop them out in the console, but when I send them to the div ID__Pokemon only the last index comes out, what is the best way to loop the pokemon names out in ID__Pokemon ?
let myApp = document.querySelector('#App');
const divPokemon = document.getElementById('ID__Pokemon');
const api_url = 'https://pokeapi.co/api/v2/pokemon/';
const pokemonData = async () => {
const response = await fetch(api_url);
const data = await response.json();
for (const item in data.results) {
let pokemon = data.results[item];+
console.log(pokemon.name);
divPokemon.innerHTML = `Pokemon: ${pokemon.name}`;
}
};
pokemonData();
<!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>Document</title>
<script src="function.js" defer></script>
</head>
<body>
<div id="App">
<div id="ID__Pokemon"></div>
</div>
</body>
</html>
doing divPokemon.innerHTML = `Pokemon: ${pokemon.name}`; replaces the content with each iteration
Here is an edit of your code which adds a new "li" element to your list, filled with the proper text content
let myApp = document.querySelector('#App');
const divPokemon = document.getElementById('ID__Pokemon');
const api_url = 'https://pokeapi.co/api/v2/pokemon/';
const pokemonData = async () => {
const response = await fetch(api_url);
const data = await response.json();
for (const item in data.results) {
let pokemon = data.results[item];
console.log(pokemon.name);
let newPokemon = document.createElement("li");
newPokemon.innerText = `Pokemon: ${pokemon.name}`;
divPokemon.appendChild(newPokemon);
}
};
pokemonData();
<!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>Document</title>
<script src="function.js" defer></script>
</head>
<body>
<div id="App">
<div id="ID__Pokemon"></div>
</div>
</body>
</html>

How do you display all images coming from the newsapi?

Hi I am trying to create a news app using the newsapi. I have managed to display the headings from the api but cant seem to manage to loop over all the images and be displayed to the screen. If you could show me how this could be done I would very much appreciate this. my code is:
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">
<link rel="stylesheet" href="css/main.css">
<title>News App</title>
</head>
<body>
<h2>BBC News</h2>
<span class="newsImage"></span>
<li class = newsList></li>
<script src="js/main.js"></script>
</body>
</html>
JavaScript
const newsList = document.querySelector(".newsList")
const newsImage = document.querySelector(".newsList")
newsImage.innerHTML =''
newsList.innerHTML= ''
var url = 'https://newsapi.org/v2/top-headlines?' +
'sources=bbc-news&' +
'apiKey=**********************';
var req = new Request(url);
fetch(req)
.then(function(response) {
return response.json()
}).then((data)=>{
console.log(data)
data.articles.map(article => {
let li = document.createElement('li')
let a = document.createElement('a')
let image = document.createElement('span')
image.innerHTML = `<img src=${data.articles.urlToImage}>`
a.setAttribute('href', article.url)
a.setAttribute('target','_blank' )
a.textContent = `${article.title}`
li.appendChild(a)
newsList.appendChild(li)
newsImage.appendChild(image)
});
})

How to create a form for comments with the ability of dynamically adding them to the list?

I need to create a form for comments with the ability to dynamically add them to the list. Each comment should have an assigned ID in consecutive order. The newest comment should be at the very bottom. Comments should be stored in the comments array. Each comment should have properties such as id (number) and text (string). Comments array must be empty when loaded initially. Each click on the "Add" button should create a new object inside the array and create element in the DOM tree.
let nextId = 1;
const comments = [];
const commentForm = document.querySelector('[data-id="comment-form"]');
const commentInput = commentForm.querySelector('[data-input="comment"]');
const button = commentForm.querySelector('[data-action="add"]');
const commentList = commentForm.querySelector('[data-id="comment-list"]');
button.addEventListener('click', () => {
const object = {};
if (commentInput.value != '') {
comments.map(() => ({ id: 'nextId++', text: commentInput.value }));
}
createElement();
});
function createElement() {
const newComment = document.createElement('li');
newComment.setAttribute('data-comment-id', comments.id);
newComment.textContent = comments.text;
commentList.appendChild(newComment);
}
<!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></title>
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<div id="root">
<form data-id="comment-form">
<textarea data-input="comment"></textarea>
<button data-action="add">Add</button>
</form>
<ul data-id="comment-list"></ul>
</div>
<script src="./js/app.js"></script>
</body>
</html>
There are some issues in your code:
You are trying to access commentList from commentForm, but that element is outside of the commentForm. Use document object to access the element.
comments is an array from which you are trying to access text property, there is text property on comments.
You should pass the current input value to the function so that you can set the newly created LI's text with the value.
You should use push() instead of map() to push an item into the array. nextId is a variable but you are using that as if it is a string, you should remove the quotes around it.
For the better user experience, I will suggest you to clear the value of the input after creating the item.
Demo:
let nextId = 1;
const comments = [];
const commentForm = document.querySelector('[data-id="comment-form"]');
const commentInput = commentForm.querySelector('[data-input="comment"]');
const button = commentForm.querySelector('[data-action="add"]');
const commentList = document.querySelector('[data-id="comment-list"]');
button.addEventListener('click', () => {
const object = {};
if (commentInput.value != '') {
comments.push({ id: nextId++, text: commentInput.value });
}
createElement(commentInput.value);
commentInput.value = '';
});
function createElement(ci) {
const newComment = document.createElement('li');
newComment.setAttribute('data-comment-id', comments.id);
newComment.textContent = ci;
commentList.appendChild(newComment);
}
<!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></title>
<link rel="stylesheet" href="./css/styles.css" />
</head>
<body>
<div id="root">
<form data-id="comment-form">
<textarea data-input="comment"></textarea>
<button type="button" data-action="add">Add</button>
</form>
<ul data-id="comment-list"></ul>
</div>
<script src="./js/app.js"></script>
</body>
</html>

Categories