Changing content in multiple columns with a single button click - javascript

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

Related

dynamic gradient value is not adding to the css

i am trying to change dynamically background-image liner gradient.i am getting the liner gradient value in console but its not changing the display! if I put the value manually in CSS it works but does not work dynamically!! what is wrong I am doing?
let inputFirst = document.getElementById("input1");
let inputSecond = document.getElementById("input2");
let buttons = document.querySelectorAll("label");
let display = document.querySelector(".container");
let color1;
let color2;
let gradientPosition = "";
inputFirst.addEventListener("input", () => {
color1 = inputFirst.value;
});
inputSecond.addEventListener("input", () => {
color2 = inputSecond.value;
});
buttons.forEach((button) => {
button.addEventListener("click", () => {
gradientPosition = button.id;
display.style.backgorundImage = `linear-gradient(${gradientPosition}, ${color1},
${color2})`;
console.log(`linear-gradient(${gradientPosition}, ${color1}, ${color2})`)
;
});
});
//linear-gradient( to right, #671313, #af1d1d)

How to create a dynamic list, which removes deleted items from an array in JS?

I have created a list, which creates a new paragraph, with the value of the input field and adds the value of the input field into an array, if the add-Button is pressed. Each paragraph has a delete Button, which removes the paragraph visually, if pressed. Now I want that the Input of the paragraph also gets removed from the array.
For example lets say, that the array usernames includes usernames[1] = Lukas, usernames[2] = Martin, usernames[3] = Bob and I want to delete the paragraph, which includes Martin.
How can I create a function, where the paragraphs content also automatically gets removed from the array usernames. I would be very thankful for some help.
Here is my code:
let name = document.getElementById('name');
let addButton = document.getElementById('button');
let output = document.getElementById('output')
let usernames = [];
addButton.addEventListener('click', function() {
usernames.push(document.getElementById('name').value)
console.log(usernames)
let paragraph = document.createElement('ul')
paragraph.innerText = document.getElementById('name').value
output.appendChild(paragraph)
let deleteButton = document.createElement('button')
deleteButton.innerHTML = "X"
paragraph.appendChild(deleteButton)
deleteButton.addEventListener('click', function() {
output.removeChild(paragraph)
})
})
You can find an element in the array by name and remove it from there:
const usernameToRemove = usernames.indexOf(name => name === paragraph.innerText);
usernames.splice(usernameToRemove, 1);
let name = document.getElementById('name');
let addButton = document.getElementById('button');
let output = document.getElementById('output')
let usernames = [];
addButton.addEventListener('click', function() {
usernames.push(document.getElementById('name').value)
console.log(usernames)
let paragraph = document.createElement('ul')
paragraph.innerText = document.getElementById('name').value
output.appendChild(paragraph)
let deleteButton = document.createElement('button')
deleteButton.innerHTML = "X"
paragraph.appendChild(deleteButton)
deleteButton.addEventListener('click', function() {
const usernameToRemove = usernames.indexOf(name => name === paragraph.innerText);
usernames.splice(usernameToRemove, 1);
output.removeChild(paragraph)
})
})
<input id="name">
<button id="button">button</button>
<div id="output">output</div>
Every time the event handler to delete an item is called, just collect all of the text of each item and convert it into an array.
del.addEventListener('click', function() {
this.closest('li').remove();
usernames = [...list.querySelectorAll('li')].map(item => item.textContent);
console.log(usernames);
});
/*
This removes an <li>, if you don't change your "paragraph" then
change 'li' to 'ul'
*/
const user = document.getElementById('user');
const add = document.querySelector('.add');
const list = document.querySelector('.list')
let usernames = [];
add.addEventListener('click', function() {
let name = user.value;
user.value = '';
usernames.push(name);
console.log(usernames);
const item = document.createElement('li');
item.textContent = name+' ';
list.append(item);
const del = document.createElement('button');
del.textContent = "X";
item.append(del);
del.addEventListener('click', function() {
this.closest('li').remove();
usernames = [...list.querySelectorAll('li')].map(item => item.textContent);
console.log(usernames);
});
});
<input id='user'><button class='add'>ADD</button>
<ul class='list'></ul>
Thank you for your answers, but unfortunately the inner Text of the delete Button gets added to the array content, if something gets deleted, because it is part of the 'li' component. I simply created a div which includes the name and the delete Button to solve the problem. But nevertheless thank you for your help. Thats the working code:
const user = document.getElementById('user');
const add = document.querySelector('.add');
const list = document.querySelector('.list')
let usernames = [];
add.addEventListener('click', function() {
let name = user.value;
user.value = '';
usernames.push(name);
console.log(usernames);
const paragraph = document.createElement('div')
paragraph.style.display = 'flex'
const item = document.createElement('li');
item.textContent = name + ' ';
list.append(paragraph);
paragraph.append(item)
const del = document.createElement('button');
del.textContent = "X";
paragraph.append(del);
del.addEventListener('click', function() {
this.closest('div').remove();
usernames = [...list.querySelectorAll('li')].map(item => item.textContent);
console.log(usernames);
});
});

Trying to get one picture at time

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>

Generating a clickable HTML link from a javascript array

I found code online that can select and print a random name from an array, and I'm trying to modify it to print a link instead of a name. I want that link to be clickable, as it would be normally in HTML. I'm not sure how to modify the javascript to do that, however.
This was my method for doing it below. But the result is that it just prints the HTML code on the page, not an interactive link. What's the better way to do this?
let btnRandom = document.querySelector('button');
let result = document.querySelector('h1');
let links = ['https://www.nytimes.com/2019/09/19/climate/air-travel-emissions.html', 'Link2', 'Link3', 'Link4', 'Link5', 'Link6', 'Link7'];
function getRandomNumber(min, max) {
let step1 = max - min + 1;
let step2 = Math.random() *step1;
let result = Math.floor(step2) + min;
return result;
}
btnRandom.addEventListener('click', () => {
let index = getRandomNumber(0, links.length-1);
result.innerText = '<a href ="' + links[index] + '"</a>';
});
Result of my current code:
You could use the innerHTML property instead of innerText to append the link as an actual HTML-element.
Or alternatively follow the approach mentioned here and create a link element and append it to the "result"-node.
Create an <a> element using Document.createElement(). Then append the element to the h1 node with Node.appendChild()
let btnRandom = document.querySelector('button');
let result = document.querySelector('h1');
const links = ['https://www.nytimes.com/2019/09/19/climate/air-travel-emissions.html', 'Link2', 'Link3', 'Link4', 'Link5', 'Link6', 'Link7'];
function getRandomNumber(min, max) {
let step1 = max - min + 1;
let step2 = Math.random() *step1;
let result = Math.floor(step2) + min;
return result;
};
btnRandom.addEventListener('click', () => {
let index = getRandomNumber(0, links.length-1);
const a = document.createElement("a");
a.textContent= links[index];
a.href= links[index];
result.appendChild(a);
});
<button>Ramdom Link</button>
<h1></h1>

Random image without repeat

When I click on the image, the image changes randomly, but it happens that some images are repeated after the click. how can I solve it?
Below is my queue.
let h1 = document.querySelector('h1')
let bigSquare = document.createElement('div')
bigSquare.id = 'bigSquare'
h1.after(bigSquare)
let images = ['01.jpg', '02.jpg', '03.jpg', '04.jpg', '05.jpg']
let randomImage = function(){
return (Math.round(Math.random()*(images.length-1)))
}
let image = document.createElement('img')
bigSquare.append(image)
image.src = images[randomImage()]
image.onclick = function(event){
event.target.src = images[randomImage()]
}
Just create a variable called say, "randNumb" that stores the random number generated in it and whenever the image is clicked, compare the previous random number with the new one and if they're different, change the img src else run the random image function again.
Check and run the following Code Snippet for a practical example of the above approach:
let h1 = document.querySelector('h1');
let bigSquare = document.createElement('div');
let randNumb = 0;
bigSquare.id = 'bigSquare';
h1.after(bigSquare);
let images = ['01.jpg', '02.jpg', '03.jpg', '04.jpg', '05.jpg'];
let image = document.createElement('img');
bigSquare.append(image);
image.src = images[randNumb];
let randomImage = function(){
let x = Math.round(Math.random()*(images.length-1)); // get random number
if (x == randNumb) {
randomImage(); // same random number so run function again
}
else {
randNumb = x;
image.src = images[randNumb]; // not same random number so change src
console.log("The image src right now is: " + image.src);
}
}
image.onclick = function(){randomImage()};
<h1></h1>

Categories

Resources