Trying to get one picture at time - javascript

I have created a function to create a bear picture but I only want one image at a time. There is a button that is resetting the other API I have but not this one. Any help or suggestions?
const numImagesAvailable = 145 //how many photos are total in the collection
const numItemsToGenerate = 1; //how many photos you want to display
const imageWidth = 360; //image width in pixels
const imageHeight = 360; //image height in pixels
const collectionID = 9396519 //Bears, the collection ID from the original url
const galleryContainer = document.querySelector('#gallery-item')
function renderGalleryItem(randomNumber) {
fetch(`https://source.unsplash.com/collection/${collectionID}/${imageWidth}x${imageHeight}/?sig=${randomNumber}`).then(function(response) {
console.log(response)
let galleryItem = document.createElement('img');
galleryItem.className = "center-bear";
galleryItem.setAttribute("src", `${response.url}`)
document.body.append(galleryItem)
})
}
for (let i = 0; i < numItemsToGenerate; i++) {
}
buttonEl.addEventListener("click", function(event) {
event.preventDefault();
listItemEl.remove();
callapi();
let randomImageIndex = Math.floor(Math.random() * numImagesAvailable);
renderGalleryItem(randomImageIndex);
});
<div id="gallery-item"></div>

const numImagesAvailable = 145; //how many photos are total in the collection
const numItemsToGenerate = 2; //how many photos you want to display
const imageWidth = 360; //image width in pixels
const imageHeight = 360; //image height in pixels
const collectionID = 9396519; //Bears, the collection ID from the original url
const urlPrefix = `https://source.unsplash.com/collection/${collectionID}/${imageWidth}x${imageHeight}/`;
const galleryContainer = document.querySelector("#gallery-item");
const button = document.querySelector("#img-getter");
function renderGalleryItem(index) {
const url = `${urlPrefix}?${index}`;
fetch(url).then(function (response) {
const img = document.createElement("img");
img.className = "center-bear";
img.setAttribute("src", `${response.url}`);
galleryContainer.append(img);
});
}
button.addEventListener("click", function (event) {
// remove old images
galleryContainer.replaceChildren();
// get new images
for (let i = 0; i < numItemsToGenerate; i++) {
const index = Math.floor(Math.random() * numImagesAvailable);
renderGalleryItem(index);
}
});
<button id="img-getter">Click</button>
<div id="gallery-item"></div>

Related

I have a misunderstanding with localStorage

I'm currently beginning to learn how to use javascript, and I have a small problem.
I'm making a minigame of 'find the random number', and I'm trying to implement a localStorage savestate that let me keep my game as it was when I closed it, but without success. Here's the part of my JS
where I'm stuck.
let Rndm = Math.floor(Math.random() * 100) + 1;
var tentatives = document.querySelector('.tentatives');
var resultat = document.querySelector('.resultat');
var plusoumoins = document.querySelector('.plusoumoins');
var valider = document.querySelector('.valider');
var essai = document.querySelector('.essai');
var nmbrmax = 1000;
var nmbrtent = 1;
let j1 = document.getElementById("j1");
let j2 = document.getElementById("j2");
var joueur1 = document.getElementById("joueur1");
var joueur2 = document.getElementById("joueur2");
let nomsjoueurs = document.getElementById("nomsjoueurs");
let tour = document.getElementById("tour");
var playerTurn = 0;
const partiesauvee = []
function sauvegarder() {
partiesauvee.push(tentatives.textContent);
partiesauvee.push(resultat.textContent);
partiesauvee.push(plusoumoins.textContent);
partiesauvee.push(nmbrmax);
partiesauvee.push(nmbrtent);
partiesauvee.push(joueur1.value);
partiesauvee.push(joueur2.value);
localStorage.setItem('sauvegard', JSON.stringify(partiesauvee))
}
function refresh() {
const partiesauvee = JSON.parse(localStorage.getItem('sauvegard'));
var tentatives = JSON.parse(localStorage.getItem('sauvegard'));
var resultat = JSON.parse(localStorage.getItem('sauvegard'));
var plusoumoins = JSON.parse(localStorage.getItem('sauvegard'));
var nmbrmax = localStorage.getItem('sauvegard');
var nmbrtent = localStorage.getItem('sauvegard');
var joueur1 = JSON.parse(localStorage.getItem('sauvegard'));
var joueur2 = JSON.parse(localStorage.getItem('sauvegard'));
}
window.addEventListener('DOMContentLoaded', refresh);
When the sauvegarder function is activated, the console.log(localstorage) find all the values,
but I can't find a way to return them to their places. Someone have an idea? Thanks !
You're storing an array. You need to assign each array element to a different DOM element.
function refresh() {
const storage = localStorage.getItem('sauvegard');
if (!storage) { // nothing saved
return;
}
const partiesauvee = JSON.parse(storage);
tentatives.textContent = partiesauvee[0];
resultat.textContent = partiesauvee[1];
plusoumoins.textContent = partiesauvee[2];
nmbrmax.textContent = partiesauvee[3];
nmbrtent.textContent = partiesauvee[4];
joueur1.textContent = partiesauvee[5];
joueur2.textContent = partiesauvee[6];
}

Changing content in multiple columns with a single button click

I am trying to change multiple columns with a single button click, after a click the image should change, the title and a phrase. I am only able to apply this to the first column. I tried iterating the columns with querySelectorAll() and searched answers in other forums.?
Also is it possible to assign a different random image to each column with the same single button click?
Thank you in advance!
const images = ['sandwich', 'cookie', 'monster', 'telegram', 'gym']
const inputName = document.getElementById('input-name');
const inputPhrase = document.getElementById('input-phrase');
const btnSubmit = document.querySelector('.input-btn');
const btnClr = document.querySelector('.clr-btn');
const row = document.querySelectorAll('.column');
const image = document.querySelector('.column img');
const title = document.querySelector('.name');
const phrase = document.querySelector('.phrase');
randomImage = Math.floor(Math.random() * images.length);
logoImage = images[randomImage];
window.addEventListener('DOMContentLoaded', function() {
// createLogo()
})
btnSubmit.addEventListener('click', function(e) {
e.preventDefault()
row.forEach(function(col) {
col.classList.add('change');
image.src = `./images/${logoImage}.png`;
title.textContent = inputName.value
phrase.textContent = inputPhrase.value
})
});
Instead of using a variable to refer to the image/name/phrase, you should reference them by col and queryselector in each iteration.
btnSubmit.addEventListener('click', function(e) {
e.preventDefault()
row.forEach(function(col) {
randomImage = Math.floor(Math.random() * images.length);
col.classList.add('change');
col.querySelector("img").src = './images/' + images[randomImage] + '.png';
col.querySelector(".name").textContent = inputName.value
col.querySelector(".phrase").textContent = inputPhrase.value
})
});

setInterval around fetch function keeps making new containers, how to just refresh api data?

Atm I am fetching data from an api and I need to compare the previous data values with the current every few seconds to indicate whether parking spots have come free, have been filled or stayed equal.
As mentioned before I am using the fetch function. Inside I create containers with createElement so each time the setInterval runs, it places the whole HTML again underneath the previous one. I'm looking for a way to be able to refresh the api data and overwrite that HTML.
Anyone know a solution for this problem?
My code looks like this
let url =
'https://datatank.stad.gent/4/mobiliteit/bezettingparkingsrealtime.json#';
let percent;
function fetchParkingData() {
fetch(url)
.then((resp) => resp.json())
.then(function(data) {
for(let i = 0; i < data.length; i++) {
let parkingData = {
name: data[i].name,
totalCapacity: data[i].parkingStatus.totalCapacity,
availableCapacity: data[i].parkingStatus.availableCapacity,
}
let mainDiv = document.getElementById('mainDiv');
let parkingDiv = document.createElement('div');
parkingDiv.className = 'parking-div';
let name = document.createElement('h2');
let totalCapacity = document.createElement('h3');
let availableCapacity = document.createElement('h4');
let indicator = document.createElement('p');
name.innerHTML = parkingData.name;
totalCapacity.innerHTML = 'Capaciteit: ' + parkingData.totalCapacity;
availableCapacity.innerHTML = 'Beschikbaar: ' + parkingData.availableCapacity;
mainDiv.appendChild(parkingDiv);
parkingDiv.appendChild(name);
parkingDiv.appendChild(totalCapacity);
parkingDiv.appendChild(availableCapacity);
percent = Math.floor(parkingData.availableCapacity / parkingData.totalCapacity * 100);
console.log(percent);
if(percent < 20) {
parkingDiv.style.backgroundColor = 'red';
} if(percent >= 20 && percent <= 50) {
parkingDiv.style.backgroundColor = 'orange';
} if(percent > 50) {
parkingDiv.style.backgroundColor = 'green';
}
};
})
.catch(function(error) {
// error handling
parkingDiv.innerHTML = 'Data could not be fetched';
});
}
setInterval(fetchParkingData , 2000);
Just clear the mainDiv before adding the data:
mainDiv.innerHTML = "";

Inserting text after a certain image using javascript

In one function I have a loop that creates 10 images using the createElement();. In the other function I have another loop that contains info that I need to add text after each picture but my code adds it at the end of all 10 pictures I need them to be after every corresponding picture.
This is the function that displays the text:
function displayAlbum(json){
for (var x = 0; x<json.length;x++){
var span1 = document.createElement("span");
span1.innerText = json[x].album;
console.log(json[x].album);
var display = document.getElementById("results");
display.appendChild(span1);
}
}
I cant individually set the id of each image because i created them in js. Thanks for the help in advance and no jquery please
for (var x = 0; x<json.length;x++){
var image = document.createElement("img");
image.id = "picture";
image.width = 100;
image.height = 100;
image.src = json[x].cover;
var display = document.getElementById("results");
display.appendChild(image);
var a = document.getElementById("artist");
var y = document.getElementById("year");
var artist = document.getElementById("artist").selectedIndex;//index of value of the switch statement
var year = document.getElementById("year").selectedIndex;//index of value of the switch statement
var realYear = y[year].text;//Value of the selected text
var realArtist = a[artist].text;//Value of the selected text
var display = document.getElementById("Results");
}
This is my second loop. I want displayalbum to appear after every picture. I cannot combine them because of other complications in the code
Try to do something like that: plunker
function displayAlbum(){
for (var x = 0; x < 10 ; x++){ // change to json.length
var span1 = document.createElement("span");
span1.innerText = 'json[x].album';
span1.id = 'span'+x;
var display = document.getElementById("results");
display.appendChild(span1);
}
}
The loop where you are creating images, give a unique id to image like image.id = "picture" + x;
Then change displayAlbum() function to use corresponding image to place the span tag.
function displayAlbum(json){
for (var x = 0; x<json.length;x++){
var span1 = document.createElement("span");
span1.innerText = json[x].album;
console.log(json[x].album);
var display = document.getElementById("results");
var img = document.getElementById("picture" + x); // use unique id of img to access it
if(img.nextSibling) { // if img is not the last node in 'results'
display.insertBefore(span1, img.nextSibling);
} else { // if img is the last node in 'results'
display.appendChild(span1);
}
}
}
You can achieve your goal with single loop and using Figure and FigCaption element , specifically created for this kind of display image with its description
var json = [{cover:"https://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Internet2.jpg/440px-Internet2.jpg", album:"test1"},{cover:"https://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Internet2.jpg/440px-Internet2.jpg", album:"test2"}];
for (var x = 0; x<json.length;x++){
var fig = document.createElement("figure");
var figCap = document.createElement("figcaption");
figCap.innerText = json[x].album;
var image = document.createElement("img");
image.id = "picture";
image.width = 100;
image.height = 100;
image.src = json[x].cover;
var display = document.getElementById("results");
fig.appendChild(image);
fig.appendChild(figCap);
display.appendChild(fig);
}
<div id="results">
</div>

Display unique image from array using javascript

I have a following code that displays random images from array.
It generates random images, but however it fails to load unique image.
For more info i would like to add that this code is for Solitaire game so i need to generate unique image.
var imgArray = ['c1.png', 'c2.png', 'd3.png', 'd4.png', 'h5.png', 'h6.png', 'd7.png', 'h8.png'];
var basePath="card/";
function imgRandom() {
for (var i = 2; i < 8; i++) {
var rand = imgArray[Math.floor(Math.random() * imgArray.length)];
var image = new Image();
image.src = basePath+rand;
image.id = 'imageid';
image.width = '100';
image.height = '130';
image.style.position = 'absolute';
document.getElementById('myimg'+i).appendChild(image);
}
}
var imgArray = ['c1.png', 'c2.png', 'd3.png', 'd4.png', 'h5.png', 'h6.png', 'd7.png', 'h8.png'];
var basePath="card/";
function imgRandom() {
var imgArrayCopy = imgArray.slice(0); //make a copy of the array.
for (var i = 2; i < 8; i++) {
var rNumber = Math.floor(Math.random() * imgArrayCopy.length);
var rand = imgArrayCopy.splice(rNumber, 1); //deletes the img from the array and returns it;
var image = new Image();
image.src = basePath+rand;
image.id = 'imageid';
image.width = '100';
image.height = '130';
image.style.position = 'absolute';
document.getElementById('myimg'+i).appendChild(image);
}
}
This should do that.

Categories

Resources