How do you add a loading GIF spinner before AOI response in vanilla javascript? - javascript

So far I've tried using the let method make the GIF a constant and attempting to switch display type is js style function. Can someone guide me into displaying GIF image before API response and hiding it when fetch() is processed.
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="./doggos.css">
<title>Dogs</title>
</head>
<body>
<h1>Doggos</h1>
<button class="add-doggo">Add Doggo</button>
<div class="doggos">
<div class="loader"><img src="./giphy (1).gif"></img></div>
</div>
<script src="./doggos.js"></script>
</body>
</html>
Javascript
const DOG_URL = "https://dog.ceo/api/breeds/image/random";
const doggos = document.querySelector(".doggos");
function addNewDoggo() {
const promise = fetch(DOG_URL);
promise
.then(function(response) {
const processingPromise = response.json(); //This line of code parses the API response into a usuable js object
return processingPromise; //this code returns a new promise and this process is called | PROCESS-CHAINING
})
.then(function(processedResponse) {
const img = document.createElement("img");
img.src = processedResponse.message;
img.alt = "Cute doggo";
doggos.appendChild(img);
});
}
document.querySelector(".add-doggo") .addEventListener("click", addNewDoggo)

Related

How to get data from specific arrays in api fetch javascript?

I am currently building a football website using LiveScore API to fetch data. Needless to say, I am actually learning API fetch using this project. This api fetch current day's fixture. I tried to get the two teams T1 and T2 with their name playing against each other in my HTML file. I got the output below.
output and api
There are overall 81 arrays, and I want some specific arrays, not all T1 & T2.Like I want Mallorca Vs Celta Vigo to be displayed, which is in 0th index of stages. Then I want data from 3rd index, which is Congo Vs Niger. Kindly suggest any method to solve this.
I wrote some HTML and JS to fetch the data.
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">
<title>Football Live Today</title>
</head>
<body>
<div>
<h2>Football Live Today</h2>
<h3>Today's Fixtures</h3>
<ul>
<li id="fixtures"></li>
</ul>
</div>
<script src="popup.js"></script>
</body>
</html>
JS
async function fetchData() {
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': '********',
'X-RapidAPI-Host': 'livescore6.p.rapidapi.com'
}
};
const res = await fetch('https://livescore6.p.rapidapi.com/matches/v2/list-by-date?Category=soccer&Date=20231801&Timezone=-7', options)
const record = await res.json()
console.log('record', record)
document.getElementById("fixtures").innerHTML = record.Stages.map(item => `
<li>${item.Events[0].T1[0].Nm} Vs ${item.Events[0].T2[0].Nm}</li>`);
}
fetchData();

javascript fetch command does not display the content on the html page

I have a simple text file in the same directory as HTML file , I used the fetch command in javascript to display the text file content in the page div section when the loading of the page finish
however, my code doesn't work and nothing has been displayed, my question is does the fetch command suitable for such a task or should I use filereader ?
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Untitled Page</title>
<meta name="generator" >
<style type="text/css">
</style>
<script type="text/javascript" defer>
const myfile=location.href.slice(0,location.href.lastIndexOf("/"))+"/a.txt"
console.log(myfile);
async function getTextFile1() {
try {
const response = await fetch(myfile, { mode: 'no-cors' });
const fileText = await response.text();
//console.log(window.location);
//console.log(window.location.href);
const tagElement = document.getElementById("about_layer");
tagElement.innerText = fileText;
} catch (error) {
console.log(error);
}
}
window.onload = getTextFile1;
</script>
</head>
<body>
<div >should be placed here </div>
<div id="about_layer">
</div>
</body>
</html>
There is nothing wrong with your code , just try running your html file using development server .
You can use Live Server visual studio code extension for that.

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)
});
})

Why loadImage is not called in p5js

I am new with p5js. I am trying to load an image using loadImage().
This is my code:
function setup (img) {
classifier.classify(img, gotResult)
appendGif(img)
}
/* This code return a random tag to use in the
url.
variable tag make reference to an array I wouldn't show here.
*/
function getRandomTag () {
const randomIndex = Math.floor(Math.random() * tags.length)
return tags[randomIndex]
}
/* This function return a random gif from giphy api */
async function getRandomGif (randomTag) {
const url = `${baseURL}${gifs}${random}?api_key=${api_key}&rating=${rating}&tag=${randomTag}`
const randomResponse = await fetch(url)
const responseJSON = await randomResponse.json()
const gif = responseJSON.data.image_url
return gif
}
/* And then, this code append the random gif to an img element in my html*/
function appendGif (gif) {
const imgElement = document.createElement('img')
imgElement.src = gif
kebabElement.appendChild(imgElement)
}
/* I am using the preload function as p5js docs say
and I load the image with loadImage function */
function preload(gif) {
classifier = ml5.imageClassifier('MobileNet');
const img = loadImage(gif)
return img
}
function gotResult (error, result) {
if (error) throw error
console.info(result)
}
async function main () {
const randomTag = getRandomTag()
const gif = await getRandomGif(randomTag)
const img = await preload(gif)
return setup(img)
}
main();
html, body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<meta name="keywords" content="gif, gifs, giphy" />
<meta name="description" content="An initial gif is presented on the page. Click the gif to retrieve other somewhat related gif based on AI recognition of the initial image." />
<meta name="author" content="Diesan Romero" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" />
</head>
<body>
<header>
<nav>
<div class="nav-wrapper">
GIF KEBAB
</div>
</nav>
</header>
<main>
<div id="kebab"></div>
</main>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js" integrity="sha512-gQVBYBvfC+uyor5Teonjr9nmY1bN+DlOCezkhzg4ShpC5q81ogvFsr5IV4xXAj6HEtG7M1Pb2JCha97tVFItYQ==" crossorigin="anonymous"></script>
<script src="https://unpkg.com/ml5#latest/dist/ml5.min.js"></script>
<script src="src/index.js" type="module" ></script>
</body>
</html>
but I am getting this error:
Uncaught (in promise) ReferenceError: loadImage is not defined
What I want to do here is load that auto generated gif with the loadImage() function.
In short, I am getting an error when calling the loadImage() function. How is possible to be not defined if I am loading p5js on my html?
Split the gif into frames
Then ....loadImage("gif1", "gif2" ......) and so on in the correct order.

Routing(?) in Vanilla JS

I need my webite to display info in a certain language, based on a query in my webite's URL (e.g. www.website.com/index.php?country=FR). How can I do that with vanilla JS and not React/Angular?
My approach:
1) JS recognizes a query in the URL (in this case- 'country=FR') and then appends a js file, which has neccessary french words in it defined by variables.
2) JS in my script tag that's in the HTML file, appends the main page markup text with template literals in it.
3)
I don't know, whether the browser fails to either fetch the language file itself or its variables. At the moment it does not render anything.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="./js/main.js"></script>
</head>
<body>
<script>
const template= `
<h1>Good Morning: ${goodmorning} </h1>
<h2>Good Evening: ${goodevening} </h2>
<h3>My name is: ${mynameis}</h3>`
function markupAppend() {
$('body').html(template);
console.log('Markup loaded')
}
markupAppend()
</script>
</body>
</html>
=========================
Main.js
var domain = window.location.href;
var FRString = domain.includes("country=FR");
var ESString = domain.includes("country=ES");
if (FRString) {
$('head').append(`<script src="./Language_files/FRENCHwords.js" />`)
}
if (ESString) {
$('head').append(`<script src="./Language_files/SPANISHwords.js" />`)
}
=========================
FRENCHwords.js
const goodmorning = 'Bonjour';
const goodevening = 'Bonsoir';
const mynameis = 'Mon nom est';
=========================
SPANISHwords.js
const goodmorning = 'Buenos dias';
const goodevening = 'Buenas tardes';
const mynameis = 'Mi nombre es';
No errors displayed, the page is just not rendering...
In Your main.js file, you are using domain.includes, it only returns the domain name but not the entire URL. You can use window.location.href.includes for this.
Instead of: domain.includes("country=FR");
Try: window.location.href.includes("country=FR");

Categories