Add divs with classes with image inside with JS - javascript

I am trying to write some JS so that the end result adds this to the HTML. I plan to have an array of images to index through and populate the page with images. Is there a simple way of doing this? Will I need to switch the classes to IDs for each image?
<div class="box">
<div class="boxInner">
<img src="http://placehold.it/480x480"/>
</div>
</div>
I have figured out how to add a div with a class.
var newInner = document.createElement('div');
newInner.className = 'boxInner';
document.getElementById("wrap").appendChild(newInner);
I also figured out how to append an image. I am stuck trying to put all of these together.
var newImage = document.createElement("img");
newImage.setAttribute("src", "http://placehold.it/480x480");
document.getElementById("wrap").appendChild(newImage);

This is one way of doing it.
var images = ["http://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg", "http://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg", "http://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg", "http://cdn.arstechnica.net/wp-content/uploads/2016/02/5718897981_10faa45ac3_b-640x624.jpg"];
for (var i = 0; i < images.length; i++) {
var container = document.getElementById("container");
var imgElement = document.createElement("img");
imgElement.src = images[i];
container.appendChild(imgElement);
}
<div id="container"></div>

Assuming you have an array with the img srcs and a div with the id of 'box':
var box = document.getElementById('box');
for (var i = 0; i < imgs.length; i++) {
var newInner = document.createElement('div');
newInner.className = 'boxInner';
var newImage = document.createElement('img');
newImage.setAttribute('src', imgs[i]);
newInner.appendChild(newImage);
box.appendChild(newInner);
}

Related

Why isn't JQuery creating a new div at each iteration?

I'm trying to make a container div for each image and its description at each iteration in my for loop, but JQuery is lumping all the image divs and description divs together into one container div, and that's messing up the whole layout.
I'm not sure why it's doing that, especially since I'm creating a new container div and appending to it within the for loop.
Here's the JSFiddle: https://jsfiddle.net/ZEZEME/wza7q3tn/4/
HTML
<div class=PgTwo></div>
JS
$.getJSON(url, function(data) {
arr = data.data;
for (var i = 0; i < arr.length; i++) {
var articleInfo = arr[i];
console.log(articleInfo);
var imgURL = articleInfo["listingimage"]['url'];
var title = articleInfo["title"];
var desc = articleInfo["listingdescription"];
if (imgURL != "") {
var imgWrapperDiv = document.createElement('div');
var imgDiv = document.createElement('div');
var descDiv = document.createElement('div');
imgDiv.id = 'imgDiv';
imgWrapperDiv.id = 'imgWrapperDiv';
descDiv.id = 'descDiv';
descDiv.textContent = desc;
var imgurlCSS = 'url("'+imgURL+'")';
$(imgDiv).css({'background-image': imgurlCSS, 'background-repeat': 'no-repeat', 'background-size': 'cover'});
$(imgDiv).append($('<a href="" id=link >'+ title +'</a>').css('text-decoration', 'none'));
$('#imgWrapperDiv').append(imgDiv);
$('#imgWrapperDiv').append(descDiv);
$('.PgTwo').append(imgWrapperDiv);
}
}
});
You're only using one id in the for loop. So you're creating the wrapper div, then setting its id but every time it sets it to the same id as before. In the DOM only one wrapper div is present then.

on button click show nex image

I want to pull image from local folder on button click, for which I have created a array with images names, and display it in the <div>.
Here is code example.
<div id="slider"></div>
<button class="btn"></button>
var img = document.createElement('IMG');
img.setAttribute('src', 'img/' + images + ".jpg");
var images = ['photo0', 'photo1', 'photo2'];//photo0.jpg,photo1.jpg,photo2.jpg are images in folder with path img/
var btn = document.querySelecotr('.btn'); //button element with onclick function
var slider = document.getElementById('slider'); //div element in which imgs will be displayed
var i = 0;
slider.appendChild(images[i]);
if (i < images.length)
i++;
else{
i=0;
}
slider.appendChild(images[i]);
Here's what you need, i quoted your images name, and made a for loop to loop through images names, and then created element, added attribute of image path (src), and then appended child to a slider.
function add_images_to_slider(){
var images = ["photo0", "photo1", "photo2"];
var slider = document.getElementById('slider');
for(var i=0; i<images.length; i++) {
var img = document.createElement('img');
img.setAttribute('src', 'img/' + images[i] + ".jpg");
slider.appendChild(img);
}
}
<div id="slider"></div>
<button id="btn" onclick="add_images_to_slider();">click me</button>
If you need one image per click, here is solution:
function add_images_to_slider(){
var images = ["photo0", "photo1", "photo2"];
var slider = document.getElementById('slider');
if (slider.getElementsByTagName('img')[0] !== undefined) slider.removeChild(slider.getElementsByTagName('img')[0]);
if (typeof add_images_to_slider.st_i == 'undefined') add_images_to_slider.st_i=0;
var img = document.createElement('img');
img.setAttribute('src', 'img/' + images[add_images_to_slider.st_i] + ".jpg");
slider.appendChild(img);
if (add_images_to_slider.st_i < images.length-1) add_images_to_slider.st_i++;
else add_images_to_slider.st_i = 0;
}
<div id="slider"></div>
<button id="btn" onclick="add_images_to_slider();">click me</button>
In the second solution i created a static variable at function, which increment untill reached the total of images in array, then restart it self.
EDITED:
I've just appended removing last image from slider, by adding this code:
if (slider.getElementsByTagName('img')[0] !== undefined) slider.removeChild(slider.getElementsByTagName('img')[0]);

How can I display the image name on mouseover?

I have 2 arrays, an image array and a price array.
I have the images displaying, but I'd like to display the price, which at the moment I have held in the image name, when I mouseover the image, is it possible?
HTML
<section id=main>
<!--populate with images from array-->
<p id="photos" class="product_display">
<script>getImage();</script>
</section>
JS
//image array for products
var imageArray = new Array();
imageArray[0]="images/coffee_prod_1.png";
imageArray[1]="images/coffee_prod_2.png";
imageArray[2]="images/coffee_prod_3.png";
imageArray[3]="images/coffee_prod_4.png";
imageArray[4]="images/coffee_prod_5.png";
imageArray[5]="images/coffee_prod_6.png";
imageArray[6]="images/coffee_prod_7.png";
//price array for products
var priceArray = ["€11.90", "€12.90", "€13.90", "€14.90", "€15.90", "€16.90", "€17.90"];
function getImage(){
var container = document.getElementById("photos");
for (var i=0; i < imageArray.length; ++i) {
var img = new Image();
img.src = imageArray[i];
img.className = "product_details";
img.name = priceArray[i];
container.appendChild(img);
}
}
I thought I might be able to add something like 'img.onmouseover = imageMouseOver(priceArray[i]);' to my getImage function, and then have something inside the function that would display the image name (ideally over the image) on mouseover. I was hoping to apply an opaque colour too so the image name might be clearer.
Any help would be appreciated!
I would suggest creating a container div for each photo, and in each container add your and like another div that contains the price. Set the price divs hidden at first with display:none or something, and then in your javascript add some listeners to show and hide it:
for (var i=0; i < imageArray.length; ++i) {
var img = new Image();
img.src = imageArray[i];
img.className = "product_details";
var container = document.createElement("div");
var price = document.createElement("div");
price.innerHTML = priceArray[i];
//Style your price and image elements so they fit in the container and the price is displayed over the image etc
container.appendChild(price);
container.appendChild(img);
container.onmouseover = function() {
container.getElementByClass("price").style.display = "block";
};
container.onmouseout = function() {
container.getElementByClass("price").style.display = "none";
};
}
You may need to fiddle with the onmouseover/out events a bit if showing the price div messes it up i.e. onmouseover is called on the layer with the highest z index instead of container, I haven't tried it but this should give you a rough idea
Working example here:
http://jsfiddle.net/0vts5291/
HTML
<section id=main>
<!--populate with images from array-->
<p id="photos" class="product_display">
</section>
JS
var imageArray = new Array();
imageArray[0]="images/coffee_prod_1.png";
imageArray[1]="images/coffee_prod_2.png";
imageArray[2]="images/coffee_prod_3.png";
imageArray[3]="images/coffee_prod_4.png";
imageArray[4]="images/coffee_prod_5.png";
imageArray[5]="images/coffee_prod_6.png";
imageArray[6]="images/coffee_prod_7.png";
//price array for products
var priceArray = ["€11.90", "€12.90", "€13.90", "€14.90", "€15.90", "€16.90", "€17.90"];
function getImage() {
var container = document.getElementById("photos");
for (var i = 0; i < imageArray.length; ++i) {
var img = new Image();
img.src = imageArray[i];
img.className = "product_details";
img.name = priceArray[i];
img.title = priceArray[i];
container.appendChild(img);
}
}
getImage();

How to tell which picture was clicked

var pic3 = document.createElement("IMG");
pic3.setAttribute("src", "img/mutantpre.jpg");
pic3.setAttribute("onclick", "display()");
pic3.setAttribute("id", "mutantpre");
pic3.setAttribute("height", "250px");
pic3.setAttribute("width", "150px");
document.getElementById("product4").appendChild(pic3);
Im trying to create a function to set all pictures to hidden when this one is clicked. However from that function I dont know which one was clicked. How do i figure out which one they clicked get the id of it so i can set the visibility of the other ones.
var pic3 = document.createElement("IMG");
pic3.setAttribute("src", "img/mutantpre.jpg");
pic3.setAttribute("onclick", "display('mutantpre')");
pic3.setAttribute("id", "mutantpre");
pic3.setAttribute("height", "250px");
pic3.setAttribute("width", "150px");
document.getElementById("product4").appendChild(pic3);
by passing same id in function of on click you can do this trick
You can also do like this
var pic3 = document.createElement("IMG");
pic3.setAttribute("src", "#");
pic3.setAttribute("onclick", "display()");
pic3.setAttribute("id", "mutantpre");
pic3.setAttribute("height", "250px");
pic3.setAttribute("width", "150px");
document.getElementById("product4").appendChild(pic3);
function display(){
el = document.getElementsByTagName("img");
for(var i =0;i<el.length;i++){
el[i].addEventListener("click",function(e){
alert("the clicked one's id is "+e.target.id);
});
}
}
Check the working Fiddle
Hope this helps!
var images = document.getElementsByTagName('img');
var activeImage = images[0]; // Assuming the first image is active at first
for(var i = 0; i < images.length; i++) {
var image = images[i];
image.onclick = function() {
activeImage.classList.remove("active");
this.classList.add("active");
activeImage = this;
}
}
The display function :
function display(element){
var list = document.getElementsByTagName("img");
for(var i=0; i<list.length ; i++){
list[i].style.opacity = "0";
}
element.style.opacity="1";
}
And in your code you must have this :
pic3.setAttribute("onclick", "display(this)");
Live example
http://jsfiddle.net/W65yA/1/

Delete Javascript generated HTML

I am programming a blackjack game and for each drawn card i create a tag <img> to display the card.
Naturally i have to delete this tag <img> after every game, but how can i do this?
Is there a way that I can remove all <img> tags within a parent?
Is there something like this: (Pseudecode)
div.removeAllChildElemtens()
or
div.removeChildElements("img");
Thanks.
If you create the elements using document.createElement('img') then you can keep a reference to them in order to delete them later.
var cards = [];
for (var i = 0; i < 52; i++)
{
var card = document.createElement('img');
// ... more initialisation of card
cards.push(card);
}
// later, to remove all
for (var i = 0; i < cards.length; i++)
{
var card = cards[i];
card.parentElement.removeChild(card);
}
Please, see the removeChild usage trick or use the new remove() function:
var div = document.getElementById("parentDivId");
var images = div.getElementsByTagName('img');
for(var i = 0; i < images.length; i++){
var img = images[i];
img.parentNode.removeChild(img);
//OR img.remove() as #Pete TNT pointed-out for modern web-browsers (FF/CH < 23)
}

Categories