I'm trying to display images on click. Those images have urls that I get from an HTMLCollection. I need to add 2 divs containing different classes, I managed to do it but I can't get the url to display my images on click. Please can someone help me ?
const image = document.querySelector('.slider-image');
image.addEventListener("click", () => {
document.getElementById("modal").classList.remove('hidden')
// Get urls (display gallery items)
let urls = image.getElementsByClassName('gallery-url');
for (let i=0; i<urls.lenght; i++) {
const getDivSliderCtn = document.getElementsByClassName("slider-container");
let div = document.createElement('div');
div.classList.add('slider-image');
let bckgImage = div.style.backgroundImage=`url(${urls})`;
div.appendChild(bckgImage);
getDivSliderCtn +=urls[i];
}
Related
I'm making a fetch call to retrieve some data on player cards.
I'm trying to display said cards and running into issues accurately parsing JSON and showing info in HTML.
Here is an example HTML heading for a card:
<h3 class="card__title">Example Card</h3>
Here is some JavaScript code I used after the fetch call:
let cardList = json.results
let cardTitle0 = cardList[0].name.toString();
How do I change the text from Example Card -> cardTitle0 from my array? This question applies to other attributes from the array and HTML objects.
You'll need to use the h3 element to get the link:
const link = document.querySelector(".card__title a");
// These can be const.
const cardList = json.results
const cardTitle0 = cardList[0].name.toString();
link.innerHTML = cardTitle0;
For multiple cards, you'd have to loop through the cardList json result and also through the elements on the page.
This is just an idea off the top of my head so I can't verify this code works or is even the best option for addressing multiple cards but hopefully it'll get you going in the right direction.
const links = document.querySelectorAll(".card__title a");
const cardList = json.results;
// Loop through the links on the page.
for (let i = 0; i < links.length - 1; i++)
{
for (let j = 0; j < cardList.length - 1; j++)
{
const title = cardList[j].name.toString();
links[i].innerHTML = title;
}
}
I'm trying to get all the img element from some website.
I opened the chrome dev tools console and put the following code which is,
var imgs = document.getElementsByTagName("img");
var i;
for (i = 0; i < imgs.length; i++) {
console.log(imgs[i]);
}
Yes, code works and returns lists of images in console but not fully.
I noticed that some img elements are not returned.
the parts that is not returened is in the following image.(the links is here)
I really wonder why these guys are not returned. Why is that?
As I said in the comment, there are no <img> elements, those are <a> elements with a css background image.
If you want to get those image urls, simply select the <a> elements, access their background-image css property and extract the urls:
var aElems = document.querySelectorAll(".J_Prop_Color a");
var images = [];
for(var i = 0; i < aElems.length; i++) {
images.push(aElems[i].style.backgroundImage.replace("url(", "").replace(")", "").replace(/\"/gi, ""))
}
console.log(images);
The .replace("url(", "").replace(")", "").replace(/\"/gi, "") part is used to remove the surrounding url("...") as per this SO answer.
Note 1: The resulting urls appear to be protocol-relative urls, where they start with // rather than an explicit protocol like https://, you may want to prepend "https:" to them before using them.
Note 2: The resulting urls are of thumbnails rather than of the full-sized images, remove the _(number)x(number).jpg part of those urls by using this replace: replace(/_\d+x\d+\.[^.]+$/, "") to get the full-size image urls:
images.push("https:" + aElems[i]
.style.backgroundImage
.replace("url(", "").replace(")", "").replace(/\"/gi, "")
.replace(/_\d+x\d+\.[^.]+$/, "")
);
The problem if you open the console and inspect the elements is like someone mention in the comments that there are no image tags, if you check the console, you will see:
a div.
You want to do:
var imgs = document.getElementsByID(IDVALUES);
var i;
for (i = 0; i < imgs.length; i++) {
console.log(imgs[i]);
}
the id is stored in the div id something like 'ks-component-??'
Most likely the answer above will not give you want since you want multiple images you would want to create an array and push the corresponding elements to it.
var img1 = ....
var img2 = etc....
....
let arr = [];
arr.push(img1);
arr.push(img2);
....
for (i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Where the ... means the list or all the variables you need
I'm trying to get the largest image, title, short description and url of top stories from the NY Times API. Before I get all the information that I need, I'm trying to just get the titles but I can't seem to get any information appearing. Is something wrong with my code?
UPDATE: I've added the element to the DOM (please see code below) however the title still hasn't been displayed. I also tried printing it in the console before but nothing printed there either.
var url = 'https://api.nytimes.com/svc/topstories/v2/science.json?api-key=MY_API_KEY'
function setup() {
noCanvas()
loadJSON(url, gotData)
}
function gotData(data) {
const articles = data.results
for (let i = 0; i < articles.length; i++) {
const title = document.createElement('h1')
title.innerText = articles[i].title
document.body.appendChild(title)
}
}
Well, you created your element, but you still need to add it to the DOM.
To create your element:
const title = document.createElement('h1')
And to add it to the DOM (to make it actually appear on your page):
document.body.appendChild(title)
But now you still need to add your actual title from the API to it:
title.innerText = articles[i].title
And all together:
const title = document.createElement('h1') // create the heading
title.innerText = articles[i].title // add the title from the API to your heading
document.body.appendChild(title) // add your heading to the DOM (this will make it appear)
Have a look at this. I answered in your dupe but here is better
let html = [];
fetch('https://api.nytimes.com/svc/topstories/v2/science.json?api-key=yourApiKey')
.then((resp) => resp.json())
.then(function(data) {
data.results.forEach(res => {
html.push(`<h1>${res.title}</h1>`);
})
document.getElementById("res").innerHTML = html.join("");
})
<div id="res"></div>
I have created 5 divs that have the same id and class with a loop. I'm now trying to populate each div with a different headline from the News API. I have managed to populate the first div with the data but I'm struggling how to insert data into the others.
Here is my attempt
// Fetch Data from API
fetch(req)
.then(r => r.json())
.then(r => {
const container = document.getElementsByClassName('postWrap')[0];
// Create div elements
for(i = 0; i < 5 ; i++) {
// Create title div
const titleDiv = document.createElement('div');
container.appendChild(titleDiv);
// Set ID & Class
titleDiv.id = 'postTitle';
titleDiv.classList.add('post-body');
// Post title data from array into div
let post = r.articles[i];
let title = post.title;
document.getElementById('postTitle').innerHTML = title;
}
});
The id of DOM should be unique. Same id of DOMs is not recommended.
Your div instances are created by your javascript code, so you can use those instance directly but get from ID.
const titleDiv = document.createElement('div');
/* Omitted.... */
// Post title data from array into div
let post = r.articles[i];
let title = post.title;
titleDiv.innerHTML = title;
I have an element displaying an image on an HTML page. This element's source is one of many different images in a JavaScript array.
I already have a script for looping through the images, creating a slideshow effect, but now I want to manually flick through the images with buttons.
This is my code so far, but I get no response when clicking the button.
function nextup()
{
imgs = [];
imgs[0] = "/snakelane/assets/images/thumb/_1.jpg"; imgs[10] = "/snakelane/assets/images/thumb/_19.jpg";
imgs[1] = "/snakelane/assets/images/thumb/_2.jpg"; imgs[11] = "/snakelane/assets/images/thumb/_20.jpg";
imgs[2] = "/snakelane/assets/images/thumb/_3.jpg"; imgs[12] = "/snakelane/assets/images/thumb/_21.jpg";
imgs[3] = "/snakelane/assets/images/thumb/_4.jpg"; imgs[13] = "/snakelane/assets/images/thumb/_22.jpg";
imgs[4] = "/snakelane/assets/images/thumb/_5.jpg"; imgs[14] = "/snakelane/assets/images/thumb/_23.jpg";
imgs[5] = "/snakelane/assets/images/thumb/_6.jpg"; imgs[15] = "/snakelane/assets/images/thumb/_24.jpg";
imgs[6] = "/snakelane/assets/images/thumb/_7.jpg"; imgs[16] = "/snakelane/assets/images/thumb/_25.jpg";
imgs[7] = "/snakelane/assets/images/thumb/_8.jpg"; imgs[17] = "/snakelane/assets/images/thumb/_26.jpg";
imgs[8] = "/snakelane/assets/images/thumb/_9.jpg"; imgs[18] = "/snakelane/assets/images/thumb/_27.jpg";
imgs[9] = "/snakelane/assets/images/thumb/_32.jpg"; imgs[19] = "/snakelane/assets/images/thumb/_28.jpg";
var pic = document.getElementById("picbox");
for(i =0; i < imgs.length; i++) {
var current = indexOf(pic.src);
var next = Math.round(current + 1);
pic.src = imgs[next];
}
}
Can anyone tell me what's wrong with my code or suggest a better way?
Multiple problems in the approach you had used. Have a look at the modified function below. Let me know if you need explanation with anything.
The following code will use an array containing image URLs and later assign in a sequential manner to an img tag on click. Enjoy!
Here you can try to see the output.
function nextup(){
//Initialized img array with 10 images, you can do it any way you want to.
var imgs = [];
for(i=0;i<10;i++){
imgs[i] = "http://lorempixel.com/output/cats-q-c-100-100-"+(i+1)+".jpg";
}
//Fetch the pic DOM element by ID
var pic = document.getElementById("picbox");
//Know what is position of currently assigned image in array.
var current = imgs.indexOf(pic.src);
var next = 0;
//Handle case if no image is present, the initial case.
if(current!=-1){
next = (current + 1)%(imgs.length);
}
//Assign the next src
pic.src = imgs[next];
}
//Scoped outside to call the function first time on load.
nextup();
I found the following problems in your code:
You tried to use indexOf without specifying the array in which the search has to be performed. Imagine s school principal asking someone to go find if John is present in the classroom without specifying a specific classroom.
For iterating through array you used a next variable which could have been a good idea if you needed an endless loop. But here since we are limited to 10 or 20 images we need to make sure that if the currently selected image is the last one, we find that next goes to 21 (assuming a total of 20 images.) and this would try to access a variable out of bounds.
Hence I've used the mod operator %.
For reference in JavaScript, 5%10 would return 5 , 15%10 would return 5 and so on. Read more about the mod operator HERE.