Hi guys!
Hi guys!
I’m working on an application which I need to get data from API an display it. Here is the API: http://swapi.co/api/films/ Each film get specific information and each character has it own information too.
Here is what I get now
And I need to make each character such as Luke Skywalker, C-3PO, R2-D2 etc. becomes clickable and every time I click on a name it will show upp the information about that character. How can I do it? Can anyone help me pls?
My code:
$(document).ready(() => {
$("#refresh").hide();
//make a function to search film
function generateUrl(path){
const url = `https://swapi.co/api/${path}`;
return url;
}
$("#btn").click(function(event){//click function for button
event.preventDefault();
//search function
var value = $("#search").val();
const path = 'films/';
var newUrl = generateUrl(path) + '?search=' + value;
//fetch data and return it to JSON
fetch(newUrl)
.then(response => response.json()).then(data => {
console.log(data.results[0].title);
for (i in data.results){ //display data base on which film the user's searching
$(".display").append(
`
<a href="#" class="title">${data.results[i].title}</a>
<p>${data.results[i].director}</p>
<span>${data.results[i].opening_crawl}</span>
`
);
//onclick function to display the characters when the title is clicked
$('.title').on("click", function(){
$(".welcome").hide();
let urls = data.results[i].characters;
fetchCharacters(urls);
$(".back").on('click', function(){
window.location.assign("index-tho-tran.html");
});
});
};
});
//function to fetch the multiple urls
function fetchCharacters(urls) {
Promise.all(urls.map(url => fetch(url)))
.then(responses => Promise.all(responses.map(res => res.text())))
.then(texts => {
addCharactersDOM(texts.map(JSON.parse));
});
}
//function to add characters to the document
function addCharactersDOM(characters) {
characters.forEach(character => {
$("#charactersContainer").append(`<div class ="character">${character.name}</div>`);
});
};
//refresh the whole page
$("#btn").hide();
$("#refresh").show();
$("#refresh").click(function(){
window.location.assign("index-tho-tran.html");
});
});
});
Thanks a lot!