Cant show the icon by using API - javascript

Hope everyone is well.
This is my HTML code.
<div class="location">
<h1 class="location-timezone">Timezone</h1>
<img src="https://openweathermap.org/img/wn/04n.png" id ="image" alt=""class="icon" />
</div>
By using "openweathermap.org" API, I am trying to get the icon value. I have already got the temperature and other things. But when it comes to change the icon value, it doesnt change.
Below, I have attached my JavaScript code:
const api = `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid={API KEY}`
fetch(api)
.then(response =>{
return response.json();
})
.then(data => {
console.log(data);
const { icon} = data.weather[0];
iconButton.src=`http://openweathermap.org/img/wn/${icon}.png`
My question is what exactly I am doing wrong. Thanks in advance.

I tested the api, but everything seems to work fine.
It's probably the way you're changing the iconButton.src.
See if this sample helps:
var sample = {"coord":{"lon":145.77,"lat":-16.92},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03n"}],"base":"stations","main":{"temp":300.15,"pressure":1007,"humidity":74,"temp_min":300.15,"temp_max":300.15},"visibility":10000,"wind":{"speed":3.6,"deg":160},"clouds":{"all":40},"dt":1485790200,"sys":{"type":1,"id":8166,"message":0.2064,"country":"AU","sunrise":1485720272,"sunset":1485766550},"id":2172797,"name":"Cairns","cod":200};
const { icon } = sample.weather[0]
document.querySelector('button').addEventListener('click', () => {
document.querySelector('.icon').src = `https://openweathermap.org/img/wn/${icon}.png`
})
<div class="location">
<h1 class="location-timezone">Timezone</h1>
<img src="https://openweathermap.org/img/wn/04n.png" id="image" alt="" class="icon" />
</div>
<button>Fetch new weather</button>

Related

How to create an alert after copied something in js

second question..
I've made a litte feature in Javascript, When you click on my logo, my email is copied.
This one works. Here you got the code.
const btnCopy = document.querySelector('.btn-copy');
const txtCopy = document.querySelector('.box p');
btnCopy.addEventListener('click', () => {
navigator.clipboard.writeText(txtCopy.innerText);
})
<div class="box">
<p style="display: none;">myemail#gmail.com</p>
<button class="btn-copy"><img src="ressources/logo.svg" class="logo"><img src="ressources/logo.svg" class="logo"></button>
</div>
I would like to know how to create an alert when the email is copied..
If you can help me
Thank you, enjoy your weekend :)
navigator.clipboard.writeText() This returns a promise and it can be handled like any async task.
const btnCopy = document.querySelector('.btn-copy');
const txtCopy = document.querySelector('.box p');
btnCopy.addEventListener('click', () => {
navigator.clipboard.writeText(txtCopy.innerText).then(() => {
//show scuccess message.
alert('Email copeid successfully')
}).catch(() => {
//show error message.
alert('Something went wrong!')
});
})
<div class="box">
<p style="display: none;">myemail#gmail.com</p>
<button class="btn-copy"><img src="ressources/logo.svg" class="logo"><img src="ressources/logo.svg" class="logo"></button>
</div>

First time using an API. Feel like I could be displaying the images a lot simpler but can't figure out how

I'm messing around with the Harry Potter API (just to learn how API's work), and have successfully gotten the images from the site onto mine. But I have created like 8 functions to do it and I feel like it could be done a lot easier. Here is the code:
JS:
// API
url = "http://hp-api.herokuapp.com/api/characters";
fetch(url)
.then(function(response){
return response.json();
})
.then(function(data){
display_image(data[1].image);
display_image2(data[2].image);
display_image3(data[3].image);
display_image4(data[4].image);
display_image5(data[5].image);
display_image6(data[6].image);
display_image7(data[7].image);
display_image8(data[8].image);
})
.catch(function(error){
console.log("Error: " + error)
});
function display_image(image_url){
document.getElementById("image1").src = image_url;
}
function display_image2(image_url){
document.getElementById("image2").src = image_url;
}
function display_image3(image_url){
document.getElementById("image3").src = image_url;
}
function display_image4(image_url){
document.getElementById("image4").src = image_url;
}
function display_image5(image_url){
document.getElementById("image5").src = image_url;
}
function display_image6(image_url){
document.getElementById("image6").src = image_url;
}
function display_image7(image_url){
document.getElementById("image7").src = image_url;
}
function display_image8(image_url){
document.getElementById("image8").src = image_url;
}
HTML:
<div class="popularContainer">
<div class="grid-1">
<img width="100%" alt="" id="image1">
</div>
<div class="grid-2">
<img width="100%" alt="" id="image2">
</div>
<div class="grid-3">
<img width="100%" alt="" id="image3">
</div>
<div class="grid-4">
<img width="100%" alt="" id="image4">
</div>
<div class="grid-5">
<img width="100%" alt="" id="image5">
</div>
<div class="grid-6">
<img width="100%" alt="" id="image6">
</div>
<div class="grid-6">
<img width="100%" alt="" id="image7">
</div>
<div class="grid-6">
<img width="100%" alt="" id="image8">
</div>
</div>
Also, more of a "if I do this" thing than a practical use right now. But let's say I put a random index on the data and got a random picture everytime the user reloaded the page. Is there a way to distinguish if there are duplicates and have one or more of them rerun so it's not a duplicate anymore? Also could I make it to where if one was a certain character it would not show up (with .style.display maybe)?
Anyways, any help is appreciated.
Come up with an array (or collection) of the <img>s to populate, and then all you need to do is iterate over the indicies of the response.
You also probably want to start at [0], not at [1] - JavaScript arrays are zero-indexed, not one-indexed.
const images = document.querySelectorAll('.popularContainer img');
fetch(url)
.then(response => response.json())
.then((data) => {
data.forEach((obj, i) => {
images[i].src = obj.image;
});
});
If the response contains more than 8 characters, slice to take only the first 8.
data.slice(0, 8).forEach((obj, i) => {
But let's say I put a random index on the data and got a random picture everytime the user reloaded the page. Is there a way to distinguish if there are duplicates and have one or more of them rerun so it's not a duplicate anymore?
When the response comes back the first time, you could put it into Local Storage. When you pick an image to display, remove it from the array of data and update the storage. On further loads, take the storage item instead of fetching again.
Creating the images from the returned response.json() in the then handler is one of the more straightforward ways this can be achieved. Using document.createElement("img") can be used to create each image tag. Then, appendChild can be used to append the images to the container directly without creating additional functions:
data.forEach((imgData, index) => {
let img = document.createElement("img");
img.id = `image${index}`;
img.src = imgData.image;
imgContainer.appendChild(img);
});
const imgContainer = document.getElementById("container");
const url = "http://hp-api.herokuapp.com/api/characters";
fetch(url)
.then(function(response) {
return response.json();
}).then(function(data) {
/* Slicing the data array down to only 8 elements will enable us to
show just the first 8 images */
const littleD = data.slice(0, 8);
littleD.forEach((imgData, index) => {
let img = document.createElement("img");
img.id = `image${index}`;
img.src = imgData.image;
imgContainer.appendChild(img);
});
})
.catch(function(error) {
console.log("Error: " + error)
});
img {
width: 100%
}
<div id="container">
</div>

Displaying Data from Javascript Fetch API - Question

I am new to working with APIs in javascript. I am looking to get input that a user puts into a box on a site (a city name) and fetch the API, to retrieve the temperature in that city. So far I have the following to fetch the API. But I am a bit lost on how to actually get that data and display it. How would I get the 'data'? I'm just not used to using APIs with Javascript and looking to learn more.
js file:
function hi() {
function temperature(input) {
const myKey = "Hidden_for_privacy";
const api = `https://api.openweathermap.org/data/2.5/weather?
q=${input}&lang=en&&appid=${myKey}&units=metric`;
fetch(api)
.then(function(response){
let data = response.json();
console.log(data);
return data;
})
Then I have this. searchUser is just representing the location the user types in:
const search = document.getElementById("searchUser");
const button = document.getElementById("submit");
button.addEventListener("click", () => {
const currentVal = search.value;
Relevant HTML:
<div class="container searchContainer">
<div class="search card card-body">
<h3>Get The Weather For a Location</h3>
<p class="lead">Enter Your Location</p>
<input type="text" id="searchUser" class="form-control"
placeholder="Location">
</div>
<br>
<div id="profile"></div>
</div>
<div class="container text-center mt-2">
<button class="btn btn-primary" id="submit">Submit</button>
</div>
<div id="content">
</div>
I think you have a few syntax errors going on before you can get into displaying data on the screen. I'd suggest concentrating on the JS implementation first to ensure you are successfully fetching data and loading it to the console. For instance, the closures in your JS might be causing problems. The hi function is creating a closure and then you are passing an argument of input into a function inside it but there is no local variables for it to grab.
Maybe try something like this to start and see what it logs:
function getTemperature() {
const myKey = "Hidden_for_privacy";
const api = `https://api.openweathermap.org/data/2.5/weather?
q=${input}&lang=en&&appid=${myKey}&units=metric`;
// .json returns a promise so you need to use .then to get the data from it synchronously
fetch(api)
.then((response) => response.json())
.then(data => console.log(data))
}

Can't change the page number of an API url I'm fetching (JavaScript)

I'm trying to change the page number of an API's endpoint using a variable instead of the actual number. It's a list of products, in each page it displays 8 itens. I was able to render it in the HTML, but I also need to make an expansive product list (which I'm having trouble with aswell).
But I cant make it work. The number is changing in the console.log, but not on the URL I'm fetching. Weirdly, it does use the variable number I placed.
Here is the full JS code:
let page = 1
const btnPage = document.querySelector('#nextPage')
btnPage.addEventListener('click', () => {
page++
console.log(page)
})
function fetchData() {
fetch(`https://frontend-intern-challenge-api.iurykrieger.vercel.app/products?page=${page}`)
.then(response => {
if(!response.ok) {
throw Error('ERROR');
}
return response.json();
}).then(data => {
console.log(data.products);
const html = data.products
.map(product => {
return `
<div class="products-item">
<img src="https:${product.image}" alt="Imagem" class="products-item-img"/>
<div class="products-item--info">
<h4>${product.name}</h4>
<p id="product-description">${product.description}</p>
<p>De: R$${product.oldPrice}</p>
<h3>Por: R$${product.price}</h3>
<p>ou 2x de R$${parseFloat((product.price) / 2)}</p>
<button>Comprar</button>
</div>
</div>
`;
//HTML generated inside the div class "products-wraper"
})
.join("");
document.getElementById('products').insertAdjacentHTML('afterbegin', html);
//.insertAdjacentHTML ratter than .innerHTML to avoid corrupting references
}).catch(error => {
console.log(error);
});
}
fetchData()
And the HTML linked that is been rendered:
<main>
<div class="products">
<div class="products-wraper" id="products"></div>
<button class="products-plus" id="nextPage">Ainda mais produtos aqui!</button>
</div>
</main>
I'm using that button to try and change the page number.
Can anyone help?
Looking at the code that has been posted, I don't see how fetchData() is called, aside from on page load.. On page load, page will always be 1, as a user hasn't had a chance to hit the button yet..
Should fetchData() be called within the event listener callback for clicking on the button?

Problems getting data from Firestore to display in DOM

I'm creating a project with the use of Firebase and I'm having some issues with getting the data inside of my database to display in the DOM due to error "setupFoodGroup is not defined"...This is likely due to a rookie coding error, but I can't seem to work out where I've gone wrong.
Current code as per below:
// Get data from database
db.collection('foodgroups').get().then(snapshot => {
setupFoodGroup(snapshot.docs);
});
// Setting Up Food Lists
const foodList = document.querySelector('.foodGroups');
const setupFoodGroup = (data) => {
let html = '';
data.forEach(doc => {
const group = doc.data();
const li = `
<li>
<div class="card bg-light mb-3" style="max-width: 20rem;">
<div class="card-body">
<h4 class="card-title">${group.title}</h4>
<p class="card-text">${group.content}</p>
</>
</div>
</li>
`;
html += li
})
foodGroups.innerHTML = html;
};
I'm then wanting to get them displaying inside the following HTML on a display page
<div class="card-body">
<ul class="foodGroups">
</ul>
</div>
Any points would be very much appreciated.
Cheers!

Categories

Resources