I would like to add an image to a website using a javascript array. I found a code and then I tried to change it. But i can't get it to work. My code does not display the image on the site.
Code I found:
const imageOut = document.querySelector('.image-out');
for (let key in images) {
let img = document.createElement('img');
img.setAttribute('data-key', key);
img.src = 'images/' + key + '.png';
imageOut.append(img);
}
html tag: <div class="image-out"></div>
Array:
const images = {"JD-03-128" :{},"JD-05-128": {},"JD-07-128": {},"JD-11-128": {},"JD-12-128": {},"JD-13-128": {},"JD-15-128": {}};
My code:
var imageOut = document.querySelector(".image-out");
for (let key in a) {
let img = document.createElement('img');
img.setAttribute('data-key', key);
img.src = 'image/'+key+'.jpg';
imageOut.append(img);
}
html tag: <div class="image-out"></div>
Array:
const a = {"a":{},"b":{},"c":{},"d":{},"e":{},"f":{},"g":{}};
image my code: jpg, name absolutely match, name folder absolutely match with folder in my code.
where is my problem ?
If you want to append (add) multiple images to an HTML document using an array, then you can do something like below.
const rootElement = document.getElementById('root')
const array = [
'https://picsum.photos/id/237/200/300',
'https://picsum.photos/id/238/200/300',
'https://picsum.photos/id/239/200/300'
]
array.forEach((src) => {
const imageElement = document.createElement('img')
imageElement.src = src
rootElement.appendChild(imageElement)
})
img{margin:5px}
<div id='root'></div>
Explanation
So basically I'm creating an <img src='' /> element for every item in the array. The items in the array are the url (src) of the images. Those are added as an attribute to the imageElement like so imageElement.src = src and finally they are appended as a child of rootElement
Related
I have a variable which stores user html input, this input might be a text or an image. I want to check if the user have entred an image or a simple text
example of user entry
this.userEntries = <p> < img src=" nature.png"></p>
txtOrImg: function () {
// expected logic
if userEntries includes tagname('img') return ... else return ...
}
Use DOMParser() and its parseFromString() Method. Then traverse it using Element.querySelector() to get a desired child Element
const data = `<p><img src="nature.png"></p>`;
const doc = new DOMParser().parseFromString(data, "text/html");
const img = doc.querySelector("img");
if (img) {
console.log("Has image!", img);
} else {
console.log("No image");
}
For multiple images use Element.querySelectorAll():
const data = `<p>
<img src="nature.png">
<img src="buildings.png">
</p>`;
const doc = new DOMParser().parseFromString(data, "text/html");
const imgs = doc.querySelectorAll("img");
imgs.forEach(img => {
console.log(`Found image: ${img.src}`);
});
I have a random image generating array and I am hoping to insert hyperlinks associated with each image but I can't seem to find an answer or solution that works; or that I can understand enough to adapt to my situation/code. I am a javascript novice just trying to learn as much as I can as I go! Thanks in advance to any help, all is appreciated!
JS as follows:
var random_images_array = ['img1.jpg', 'img2.jpg', 'img3.jpg'];
function getRandomImage(imgAr, path) {
path = path || 'img/'; // default path here
var num = Math.floor( Math.random() * imgAr.length );
var img = imgAr[ num ];
var imgStr = '<img src="' + path + img + '" alt = "">';
document.write(imgStr); document.close();
}
HTML:
<div id="heroImage" style="text-align: center">
<script type="text/javascript">getRandomImage(random_images_array, 'img/heroImage/')</script>
</div>
Here's what I think you're trying to accomplish. Note: don't use document.write -- that has very specific uses and this isn't a good one. Rather use the innerHTML property (and there are other ways too). I modified the code so you could see the result in the snippet.
let random_images_array = [{
img: "https://picsum.photos/200/300?1",
link: "https://google.com"
},
{
img: "https://picsum.photos/200/300?2",
link: "https://yahoo.com"
},
{
img: "https://picsum.photos/200/300?3",
link: "https://loren.picsum.com"
}
];
function getRandomImage(imgAr, path) {
path = path || 'img/'; // default path here
path = ''; // JUST FOR S.O. TESTING
let num = Math.floor(Math.random() * imgAr.length);
let img = path + imgAr[num].img;
let imgStr = `<a href='${imgAr[num].link}'><img src="${img}" alt="" border="0" /></a>`;
document.querySelector('#heroImage').innerHTML = imgStr;
}
window.addEventListener('DOMContentLoaded', () => {
getRandomImage(random_images_array, 'img/heroImage/')
})
<div id="heroImage" style="text-align: center">
</div>
picsum answers GETs from picsum.photos/width/height by redirecting to a random image with the requested dimensions.
In order to have the image and the link match, you must make the picsum GET request and get the redirect URL from the response "Location" header. That's the URL that should be placed in the DOM.
After running the snippet, right-click the image and open it in new tab. Note the same image appears. Using the original GET url as the href will direct user to a new random image.
// super simple promise-returning http request
async function get(url) {
return new Promise(resolve => {
const xmlHttp = new XMLHttpRequest();
xmlHttp.addEventListener("load", () => resolve(xmlHttp));
xmlHttp.open("GET", url);
xmlHttp.send();
});
}
async function getRandomImage(width, height) {
const url = `https://picsum.photos/${width}/${height}`;
let res = await get(url);
// this is the important part: we need the redirect url for the image
const redirectURL = res.responseURL
const html = `<a href='${redirectURL}' target='_blank'><img src="${redirectURL}" alt=""/></a>`;
const el = document.querySelector('#heroImage')
el.innerHTML = html;
}
getRandomImage(200, 300)
<div id="heroImage" style="text-align: center">
</div>
Notice that we don't need to fool around with a random pick from an array of URLs. picsum does the randomizing on the initial GET.
I have a webpage I am trying to build. I want to create a grid of images and titles that render dynamically with javascript. I have an array of objects in my file that have a image src and title.
I want to iterate through the the array of objects and then have each item render within the grid by appending to the parent div.
What is happening is that it is only showing the last item in the object and there is an issue with the image url that is loading with the titls. It is currently only showing one image.
I need help figuring this out.
Here is the JS moments array:
const moments = [
{
image: "./inages/pexels-ali-pazani-2613260.jpg",
title: "WIDE BRIM HAT"
},
{
image: "./inages/pexels-jonas-togo-3072141.jpg",
title: "OSCAR WILDE"
},
{
image: "./inages/pexels-simon-robben-977796.jpg",
title: "LOOK! A BIRD"
},
{
image: "./inages/pexels-kira-schwarz-9169378.jpg",
title: "BUBBLES!"
},
{
image: "./inages/pexels-maksim-goncharenok-5046542.jpg",
title: "CHAMPAGNE POPPY"
},
{
image: "./inages/pexels-eberhard-grossgasteiger-4406335.jpg",
title: "ERUPTION"
},
{
image: "./inages/pexels-suliman-sallehi-1484771.jpg",
title: "BOND. JAMES BOND"
},
{
image: "./inages/pexels-nataliya-vaitkevich-5712923.jpg",
title: "1327 STEPS"
},
{
image: "./inages/pexels-a-koolshooter-5601107.jpg",
title: "DIOR"
},
]
I have a function that will run and create the structure that I want to generate as a final result.
This is the final result that I want...
<div class="featured-item">
<img class="featured-image" src="./inages/pexels-jonas-togo-3072141.jpg"/>
<p class="featured-title">OSCAR WILDE</p>
</div>
<div class="featured-item">
<img class="featured-image" src="./inages/pexels-simon-robben-977796.jpg"/>
<p class="featured-title">LOOK! A BIRD</p>
</div>
<div class="featured-item">
<img class="featured-image" src="./inages/pexels-kira-schwarz-9169378.jpg"/>
<p class="featured-title">BUBBLES!</p>
</div>
<div class="featured-item">
<img class="featured-image" src="./inages/pexels-maksim-goncharenok-5046542.jpg"/>
<p class="featured-title">CHAMPAGNE POPPY</p>
</div>
This is the function that I have
let featuredMomentsDiv = document.getElementById('featured-grid')
function CreateFeaturedGridItem(){
let newFeaturedDiv = document.createElement('div')
let newFeaturedImage = document.createElement('img')
let newFeaturedTitle = document.createElement('p')
newFeaturedDiv.classList.add('featured-item')
newFeaturedImage.classList.add('featured-image')
newFeaturedTitle.classList.add('featured-title')
for(let i = 0; i < moments.length; i++){
let currentImage = moments[i]['image']
let currentTitle = moments[i]['title']
newFeaturedImage.src = currentImage
newFeaturedTitle.innerHTML = currentTitle
newFeaturedDiv.appendChild(newFeaturedImage)
newFeaturedDiv.appendChild(newFeaturedTitle)
// I want to append each div structure to the parent element
// the parent element is featuredMomentsDiv
featuredMomentsDiv.append(newFeaturedDiv)
}
}
CreateFeaturedGridItem();
I want each structure to build and append to the div featuredMomentsDiv.
This is what is currently printing when I run the code:
enter image description here
You can map through the array, construct the corresponding string with the properties insert at the right positions, then join the result:
const moments=[{image:"./inages/pexels-ali-pazani-2613260.jpg",title:"WIDE BRIM HAT"},{image:"./inages/pexels-jonas-togo-3072141.jpg",title:"OSCAR WILDE"},{image:"./inages/pexels-simon-robben-977796.jpg",title:"LOOK! A BIRD"},{image:"./inages/pexels-kira-schwarz-9169378.jpg",title:"BUBBLES!"},{image:"./inages/pexels-maksim-goncharenok-5046542.jpg",title:"CHAMPAGNE POPPY"},{image:"./inages/pexels-eberhard-grossgasteiger-4406335.jpg",title:"ERUPTION"},{image:"./inages/pexels-suliman-sallehi-1484771.jpg",title:"BOND. JAMES BOND"},{image:"./inages/pexels-nataliya-vaitkevich-5712923.jpg",title:"1327 STEPS"},{image:"./inages/pexels-a-koolshooter-5601107.jpg",title:"DIOR"}];
const HTML = moments.map(e => `<div class="featured-item"><img class="featured-image" src="${e.image}"/><p class="featured-title">${e.title}</p></div>`).join('')
document.write(HTML)
If the image and title properties contain HTML which you would like to escape, you can construct the elements and set their src and textContent:
const moments=[{image:"./inages/pexels-ali-pazani-2613260.jpg",title:"WIDE BRIM HAT"},{image:"./inages/pexels-jonas-togo-3072141.jpg",title:"OSCAR WILDE"},{image:"./inages/pexels-simon-robben-977796.jpg",title:"LOOK! A BIRD"},{image:"./inages/pexels-kira-schwarz-9169378.jpg",title:"BUBBLES!"},{image:"./inages/pexels-maksim-goncharenok-5046542.jpg",title:"CHAMPAGNE POPPY"},{image:"./inages/pexels-eberhard-grossgasteiger-4406335.jpg",title:"ERUPTION"},{image:"./inages/pexels-suliman-sallehi-1484771.jpg",title:"BOND. JAMES BOND"},{image:"./inages/pexels-nataliya-vaitkevich-5712923.jpg",title:"1327 STEPS"},{image:"./inages/pexels-a-koolshooter-5601107.jpg",title:"DIOR"}];
const container = document.getElementById("featured-grid")
moments.forEach(e => {
const item = document.createElement('div')
const img = document.createElement('img')
const paragraph = document.createElement('p')
img.classList.add('featured-image')
paragraph.classList.add('featured-title');
img.src = e.image;
paragraph.textContent = e.title;
item.appendChild(img)
item.appendChild(paragraph)
container.appendChild(item);
})
<div id="featured-grid" class="featured-grid"></div>
You have to create a new element for every loop cycle.
let featuredMomentsDiv = document.getElementById('featured-grid')
function CreateFeaturedGridItem(){
for(let i = 0; i < moments.length; i++){
let newFeaturedDiv = document.createElement('div')
let newFeaturedImage = document.createElement('img')
let newFeaturedTitle = document.createElement('p')
newFeaturedDiv.classList.add('featured-item')
newFeaturedImage.classList.add('featured-image')
newFeaturedTitle.classList.add('featured-title')
let currentImage = moments[i]['image']
let currentTitle = moments[i]['title']
newFeaturedImage.src = currentImage
newFeaturedTitle.innerHTML = currentTitle
newFeaturedDiv.appendChild(newFeaturedImage)
newFeaturedDiv.appendChild(newFeaturedTitle)
// I want to append each div structure to the parent element
// the parent element is featuredMomentsDiv
featuredMomentsDiv.append(newFeaturedDiv)
}
}
I am trying to create a web-app which allows the user to upload an image from their pc, and from that, it will create an object, and add it into an array (to have record of it and its properties) and also display it on screen.
I have created a codepen: https://codepen.io/eve_mf/pen/XebVWv
html:
<form id="form" action="" method="post" enctype="multipart/form-data">
<div class="file-uploader-wrapper">
<input id="file-uploader" class="file-uploader-input" type='file' onchange="retrieveImageFromUpload(this);"/>
<button class="file-uploader-btn" type="button">Select an image</button>
</div>
</form>
<div id="map-view"></div>
js:
let allImages = [];
let displayImages = document.getElementById("map-view");
let imagesCounter = 0;
$(".file-uploader-btn").click(function() {
$("#file-uploader").click();
});
function retrieveImageFromUpload() {
let imgReader = new FileReader();
imgReader.readAsDataURL(document.getElementById("file-uploader").files[0]);
imgReader.onload = function (imgReaderEvent) {
let imageUploadedName = imgReaderEvent.target.result;
return readUploadedImage(imageUploadedName);
};
}
//create HTML image from the uploaded img
function readUploadedImage(imageUploadedName) {
imagesCounter++;
let img = document.createElement('img');
img = {
"id": 'screen-' + imagesCounter,
"src": imageUploadedName,
"alt": 'Default-alt'
};
allImages.push(img);
console.log(allImages);
var imgHTML = img.cloneNode(true);
imgHTML = "<img id='"+ img.id + "' src='" + img.src + "' alt ='" + img.alt + "' />";
displayImages.appendChild(imgHTML);
console.log("-------------");
}
My problem begins after creating the image element; I think I am getting confused but I can not really understand where or why.
I create an image with "let img = document.createElement('img');"
Then, I set its properties as object, and I think it is here where I get messed up. Then, I put this object into my array (called allImages), so, this is what I want so far.
But then, a part from adding this object into my array, I want to display it as an HTML image, I am trying this with "appendChild", But definitely is something really wrong because I get the error that I am not operating with a node element.
Can someone give me a push to the right path?
Thank you
Here I corrected your codepen.
You have to create a DOM element in order to add it to the page:
var imgHTML = document.createElement("IMG");
imgHTML.setAttribute("id", img.id);
imgHTML.setAttribute("src", img.src);
Tested and working.
You're redifining img as a regular object literal, loosing the image in the process.
You have to set the properties one by one
let img = document.createElement('img');
img.id = 'screen-' + imagesCounter;
img.src = imageUploadedName;
img.alt = 'Default-alt;
What you're doing is pretty much the same as
let x = 'image';
x = {id : 4};
console.log(x); // no suprise, it's just {id : 4} and the string was lost
It was a node element:
let img = document.createElement('img');
But then you got rid of the node element and replaced it with a custom object:
img = {
//...
};
This completely removed the node element, now all img has is your custom object with those three properties. Instead of creating a new object, just set the properties directly:
let img = document.createElement('img');
img.id = 'screen-' + imagesCounter;
img.src = imageUploadedName;
img.alt = 'Default-alt';
I have a message or string which contain both text as well as images as below.
var text = '<span class="user_message">hiiiiiii <img title=":benztip" src="path../files/stickers/1427956613.gif"> <img src="path../files/stickers/416397278.gif" title=":happy"></span>';
Before appending this to the the chat div i want to replace the src of the images to a default image.
How can i do that with Javascript or Jquery?
You can wrap your string into a jQuery-object and use the .find()-method to select the images inside the message-string:
var msg = '<span class="user_message">hiiiiiii<img title=":benztip" src="path../files/stickers/1427956613.gif" /><img src="path../files/stickers/416397278.gif" title=":happy" /></span>';
var $msg = $(msg);
$msg.find('img').attr('src', 'path_to_img');
$("#chat_content").append($msg);
Demo
Something like this in plain old JavaScript might work for you
// save string to temporary element
var tmp = document.createElement('div');
tmp.innerHTML = '<span class="user_message">hiiiiiii <img title=":benztip" src="path../files/stickers/1427956613.gif"> <img src="path../files/stickers/416397278.gif" title=":happy"></span>';
// loop through images
var imgs = tmp.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
var src = imgs[i].getAttribute("src"); // get current src
src = "http://placehold.it/100x100"; // do something with path
imgs[i].setAttribute("src", src); // set it
}
// output or whatever
document.writeln(tmp.innerHTML);
Try this for javascript solution, will work in older browsers too.
var spanNode = document.getElementById("spanId");
spanNode.getElementsByTagName("img")[0].src = "Src1";
spanNode.getElementsByTagName("img")[1].src = "Src2";
You can also use For loop for tagnames if there are more than 2 images.
document.getElementById("image_id").src="default_img_name";