i have fetchTeam(teamName) function which gets an array of players and displays them in HTML. and another function that takes a player name as a parameter and displays the player stats. Something like this....
let result = document.getElementById("result");
let teamName;
const fetchTeam = async (teamName) => {
teamName = document.getElementById("teamName").value;
const response = await fetch(`http://localhost:3000/${teamName}`);
const data = await response.json();
let team = data.teamStats;
let players = data.playerStats;
const teamName = team[0].Name;
const logo = team[0].Logo;
const WL = team[0].WL;
result.innerHTML = `
<br><div class="top">
<h3>${teamName}</h3>
<h4>Win / Loss: ${WL}</h4>
<img src=${logo}></div>
<div class="flex-container">
<div class="flex-child">
<button class='name' onclick="fetchPlayer("${players[0][0].Player}")> ${players[0][0].Player} </button> ...
`
That all works fine except the onclick fetchPlayer function at the bottom.... Heres the code for that:
const results = document.getElementById("results");
const fetchPlayer = async (player) => {
const response = await fetch(`https://get-player.herokuapp.com/${player}`);
const data = await response.json();
results.innerHTML = `
<br>
<div class="layout">
<div class="child"><img src="${data.sprite}[0]"><br>${data.mons[0]}</div>
`
As you can see, i want to display the team members and then clicking on a member name will show their stats.
edit: format
There are several issues in your code.
First, you redeclare teamName in your fetchTeam function. That cannot work.
const fetchTeam = async (teamName) => {
teamName = document.getElementById("teamName").value;
...
const teamName = team[0].Name;
}
Second, your button syntax is incorrect :
<button class='name' onclick="fetchPlayer("${players[0][0].Player}")>
should be
<button class='name' onclick="fetchPlayer('${players[0][0].Player}')">
Third, as pointed out in this answer, in your fetchPlayer function
<img src="${data.sprite}[0]"> should be <img src="${data.sprite[0]}">
In the fetchPlayer function,
Change <img src="${data.sprite}[0]"> to <img src="${data.sprite[0]}">
Related
I m want implement pagination with js and apirest from themoviedb.
Response give me a total_pages and total_results. I ve 2 buttons, prev and next.
Thanks in advance for help me to understand. Best regards.
I´m student and now i want create my repo as exercise and practice
My full code
//buttons
const btnAtras = document.getElementById('btnAtras')
const btnAdelante = document.getElementById('btnAdelante')
//api props
const key ='MyKey';
const lang ='es-ES';
let page =1
const fetch1 = fetch('https://api.themoviedb.org/3/movie/now_playing?api_key='+key+'&language='+lang+'&page='+page).then(resp=> resp.json())
const fetch2 = fetch('https://api.themoviedb.org/3/genre/movie/list?api_key='+key+'&language='+lang).then(resp=>resp.json())
//multifetch request
const allData = Promise.all([fetch1,fetch2])
allData.then(data=>{
let genres = data[1].genres
let movies = data[0].results
let currentPage = data[0].page;
let totalPages = data[0].total_pages
console.log(currentPage)
console.log(totalPages)
//map for taking all genre_ids to resolve genre_names
for (let movie of movies) {
movie.genres = genres.filter((item) => ((movie.genre_ids.indexOf(item.id) >= 0)));
movie.genre_names = movie.genres.map(item => item.name);
}
//getting all data
getCardFilm(movies);
})
//function to create each card template
function getCardFilm (data){
const cardContent = document.getElementById('playingNow');
let content = '';
const _baseUrlImg = 'https://image.tmdb.org/t/p/original';
data.forEach(film =>{
const {title,genre_names, poster_path, release_date, overview, id} = film;
content += `
<div class='card m-2' style='width: 22rem;' >
<img src='${_baseUrlImg+poster_path}' class='card-img-top' style='height:460px;width:100%;' alt='Imágen de la pelicula'>
<div class='card-header text-start'style='height: 6rem;'>
<h5 class='card-title'>${title}</h5>
<p class='card-text text-muted'>Lanzamiento: ${release_date}</p>
</div>
<div class='card-body text-start' id='linkFilm'>
<p class='card-text m-0'>${overview}</p>
</div>
<div class="card-footer text-muted " style='width:100%;
height:4rem;'>
<span class='text-center text-dark'>
${genre_names}
</span>
</div>
</div>
`
})
cardContent.innerHTML=content;
}```
i'm having a trouble using the id from a template string item
const elementoParaInserirJogosNaLista = document.getElementById("listaJogos");
function exibirJogosNaTela(listaDeJogos) {
elementoParaInserirJogosNaLista.innerHTML = "";
listaDeJogos.forEach((jogo) => {
elementoParaInserirJogosNaLista.innerHTML += `
<div class="jogo">
<a href="paginajogo.html">
<img class="jogo__imagem" src="${jogo.imagem}" alt="${jogo.titulo}" />
</a>
<h2 class="jogo__titulo">${jogo.titulo}</h2>
<p class="jogo__preco" id="preco">R$${jogo.preco}<a ><img class="jogo__carrinho" id="addCarrinho" src="./images/addcart.png" alt="Adicionar ao carrinho"/></p><a/>
</div>
`;
});
}
i've tried to use the id "addCarrinho" and nothing happens
i'm newb on developing
const botoesAddCarrinho = [];
botoesAddCarrinho = document.querySelectorAll(".jogo__carrinho");
botoesAddCarrinho.forEach((evento) =>
evento.addEventListener("click", addNoCarrinho)
);
function addNoCarrinho () {
console.log('ok')
}
i've changed the selector to by the class, but nothings happens, is like the nothing was selected
i'm using the exibirNaTela on the fetch with the json
let jogos = [];
const endpointDaAPI ="jogos.json"
getBuscarJogosDaAPI();
async function getBuscarJogosDaAPI() {
const respost = await fetch(endpointDaAPI);
jogos = await respost.json();
exibirJogosNaTela(jogos.jogos);
}
I am trying to add an event listener to my "degree section div" but it is not working nor am I getting any errors. I have tried multiple ways of traversing the DOM to reach the "degree-section" div but to no avail.
Any kind of help is welcome and appreciated
Code:
let city = document.querySelector('#city');
let searchbtn = document.querySelector('.search-btn');
let city_name = document.querySelector('.city-name');
let temp = document.querySelector('.temp');
let feels_like = document.querySelector('.feels-like');
let humidity = document.querySelector('.humidity');
let locationIcon = document.querySelector('.weather-icon');
let checkbox = document.getElementById('celcius');
let weather_sec = document.querySelector('.weather-info');
let degree_section = weather_sec.firstElementChild;
let degree_section_span = degree_section.getElementsByTagName('span')[0];
//let wind = document.querySelector('.wind');
async function getUrl(city) {
try {
let theUrl = url + city + '&appid=' + apiKey;
let response = await fetch(theUrl, {
mode: 'cors'
})
let data = await response.json();
//Get data from api and change html content based on the recieved data
let temp_data = data.main.temp
temp.textContent = temp_data;
let feels_like_data = data.main.feels_like;
feels_like.textContent = feels_like_data + "K";
let humidity_data = data.main.humidity;
humidity.textContent = humidity_data;
let {
icon
} = data.weather[0];
locationIcon.innerHTML = `<img src="icons/${icon}.png">`;
//change K to C
degree_section.addEventListener('click', () => {
//logging a message just to check if it is working
console.log("c")
})
} catch (err) {
let error = document.createElement('span')
error.className = "error";
error.textContent = "Location does not exist"
let top_center_div = document.querySelector('.top-center')
top_center_div.appendChild(error)
city_name.textContent = "No city found"
}
}
searchbtn.addEventListener('click', (e) => {
let cityName = city.value;
city_name.textContent = cityName
console.log(cityName)
getUrl(cityName)
})
<body>
<div class="loc-container">
<div class="location">
<h1 class="city-name">City</h1>
<div class="weather-icon"><img src="icons/unknown.png" /></div>
</div>
</div>
<div class="weather-info">
<div class="degree-section">
<h2 class="temp">0.0</h2>
<span>K</span>
</div>
<div class="info-section">
<div class="info-flex">
<h3 class="feels-like">0K</h3>
<h4>Feels Like</h4>
</div>
<div class="info-flex">
<h3 class="humidity">0</h3>
<h4>Humidity</h4>
</div>
<div class="info-flex">
<h3 class="wind">0</h3>
<h4>Wind</h4>
</div>
</div>
</div>
<div class="top-center">
<div class="form">
<input type="text" name="city" id="city" required>
<label for="city" class="label-name"><span class="search-name">Search City...</span></label>
</div>
<!-- <i class="fas fa-search search-btn"></i> -->
<i class="material-icons search-btn" style="font-size: 35px;">search</i>
</div>
<script src="weather.js"></script>
</body>
This is what "data" looks like
{"coord":{"lon":72.8479,"lat":19.0144},"weather":[{"id":711,"main":"Smoke","description":"smoke","icon":"50d"}],"base":"stations","main":{"temp":303.14,"feels_like":303.45,"temp_min":301.09,"temp_max":303.14,"pressure":1014,"humidity":45},"visibility":2500,"wind":{"speed":3.09,"deg":120},"clouds":{"all":20},"dt":1638773692,"sys":{"type":1,"id":9052,"country":"IN","sunrise":1638754125,"sunset":1638793848},"timezone":19800,"id":1275339,"name":"Mumbai","cod":200}
Thank you in advance!
I believe the problem is with
let degree_section_span = degree_section.getElementsByTagName('span')[0];
since it selects the wrong element. Try changing it to
let degree_section_span = weather_sec.querySelector('.check');
and see if it works. You can also change the variable name to something more appropriate, while you're at it.
EDIT:
I think this is what you're trying to do. For the sake of siplicity , I removed everything not related to temp:
let target = weather_sec.querySelector("div.check"),
temp_data = data.main.temp;
temp.textContent = temp_data;
target.addEventListener('click', () => {
cel = parseInt(temp_data) - 273.15;
temp.textContent = cel.toFixed(2);
temp.nextElementSibling.textContent = "C";
});
So after 48hrs of debugging I finally figured out what is wrong. If you see in my HTML I have a div.top-center at the bottom. And due to some dimension issues in my css file the height of div.top-center spanned the entire page so essentially all of my divs were being wrapped inside div.top-center so even if I assigned a click event to my div.degree-section the target was always div.top-center and that is why the click event was not showing the proper output.
I am currently iterating through a list of movies and want to be able to make each element clickable and pass their respective movie information to the click event.
Here is how I iterate through my data. I want to be able to pass the movie information to the click event so that when I click on a movie, I can display its information :
const APIKEY = 'api_key=blabla....';
const BASE_URL = 'https://api.themoviedb.org/3';
const API_URL = BASE_URL + '/discover/movie?sort_by=popularity.desc&' + APIKEY;
const IMG_URL = 'https://image.tmdb.org/t/p/w500';
const SEARCH_URL = BASE_URL + '/search/movie?' + APIKEY;
const main = document.getElementById('main')
const form = document.getElementById('form')
const search = document.getElementById('search')
getMovies(API_URL);
function getMovies(url) {
fetch(url).then(res => res.json()).then(data => {
showMovies(data.results);
console.log(data.results)
})
}
function showMovies(data){
main.innerText = '';
data.forEach((movie, index) => {
let {title, poster_path, release_date, overview} = movie;
let movieEl = document.createElement('div');
movieEl.classList.add('movie');
movieEl.innerHTML = `
<div onclick="showMovieInfo(${movie[index]})" style="cursor: pointer;">
<img src="${IMG_URL + poster_path}" alt="${title}">
<div class="movie-info">
<h3>${title}</h3>
<span>${release_date.slice(0,4)}</span>
</div>
<div class="overview">
${overview}
</div>
</div>
`
main.appendChild(movieEl)
})
}
For Now i just want to be able to console.log the movie info for each
function showMovieInfo(movie) {
console.log(movie)
}
Currently I get this error when I click on an element: Uncaught SyntaxError: Unexpected identifier
Do you guys know what I could do to make it work?
The problem here ist that the "movie" object don´t exist in the "innerHTML" context. One Solution would be to serialise the movie Object or pass the Index and than get the Object from the data Array.
You can´t pass an Object to innerHTML so you have to pass a Primitive values like string or number.
const main = document.getElementById('main');
const IMG_URL = "/"
const data = [{title: "New Movie", poster_path:"",release_date:"2021-10-31", overview:"nice movie" }];
function showMovieInfo(movieId){
console.log(data[movieId])
}
function showMovies(data){
main.innerText = '';
data.forEach((movie, index) => {
let {title, poster_path, release_date, overview} = movie;
let movieEl = document.createElement('div');
movieEl.classList.add('movie');
movieEl.innerHTML = `
<div onclick="showMovieInfo(${index})" style="cursor: pointer;">
<img src="${IMG_URL + poster_path}" alt="${title}">
<div class="movie-info">
<h3>${title}</h3>
<span>${release_date.slice(0,4)}</span>
</div>
<div class="overview">
${overview}
</div>
</div>
`
main.appendChild(movieEl)
})
}
showMovies(data);
<div id="main">
</div>
I have two different functions and I created a third function which I use to display some pieces of information. What I am trying to do is: I want to display photographerPrice which is inside of the photographerProfil function and the sum of all the likes which is inside of the photographerWork function, those two elements I want to display inside my third function likesAndPrice.
I tried to call the function likesAndPrice inside two of the functions photographerProfil and photographerWork using two arguments and two parameters: it doesn't work, it only works when I use one single parameter either for likes or the price but not both. How can I display the two of them Price and Likes in one place ?
The result I want:
photographerProfil Function code
function photographerProfil(JsonData){
const id = window.location.search.split('id=')[1];
const photographers = !id ? JsonData.photographers : JsonData.photographers.filter(photographer => photographer.id == id);
photographers.forEach(element => {
const domDiv = document.getElementById('photographer-container');
const newDiv = document.createElement('div');
const photographerPrice = element.price;
const profilTemplate = `
<div class="profil-container">
<h2>${element.name}</h2>
<p>${element.city}, ${element.country}</p>
<p class="tagline">${element.tagline}</p>
<p>${element.tags.map(tag => `<button class='tags'>#${tag}</button>`).join(" ")}</p>
<button id="test">Contactez-moi</button>
<div class="photoBox">
<img src="${element.portrait}" alt="photo">
</div>
</div>
`
newDiv.innerHTML = profilTemplate;
domDiv.appendChild(newDiv);
showModal(); // function invoked here
photographerWork(JsonData, element) // function invoked here
})
}
photographerWork Function code
function photographerWork(JsonData, homeElement){
let sum = 0;
const homeElt = homeElement.id;
JsonData.media.forEach(element => {
if(homeElt == element.photographerId){
const domDiv = document.getElementById('photographer-work');
const newDiv = document.createElement("div");
sum += element.likes;
const workTemplate = `
<div class="photo-box">
<div class="photo">
${videoOrImage(element.image, element.video, element)}
</div>
<div class="text">
<p> ${element.tags}<b>${element.price} €   ${element.likes} <i class="fas fa-heart"></i></b></p>
</div>
</div>
`
newDiv.innerHTML = workTemplate;
domDiv.appendChild(newDiv);
}
})
likesAndPrice(sum) // function invoked here
}
And the Function in which I want to display the Likes and Price
//total likes and price
function likesAndPrice(sum){
const domDiv = document.getElementById('photographer-work');
const newDiv = document.createElement("div");
const likesAndPriceTemplate = `
<span>${sum} <i class="fas fa-heart"></i></span>
<span></span>
`
newDiv.classList.add('likesAndPriceContainer')
newDiv.innerHTML = likesAndPriceTemplate;
domDiv.appendChild(newDiv)
}
Assuming you can also call likesAndPrice() in your photographerProfil function
Inside photographerWork at the last line you can return the local sum variable
return sum;
Now when you invoke the function at photographerProfil it returns the sum
let sum = photographerWork(JsonData, element) // function invoked here
Now you have your sum and the photographerPrice both in your photographerprofil function available this means you can call here the likesAndPrice function.
likesAndPrice(sum, photographerPrice) // function invoked here
Note: you have to update the signature where you define the function likeAndPrice() and add another parameter to it
function likesAndPrice(sum, <param>){