I am trying to append two different JSON items per div. I empty the div before looping through the json and then append the objects.
But I need to append two per div and each item has to be different.
Eg. div1 has img1 & img2, div2 has img3 & img4 etc.
This is the result I am getting -
<div class="gallery-sub-slider">
<div>
<img class="img1">
<img class="img2">
<img class="img3">
<img class="img4">
<img class="img5">
</div>
<div>
<img class="img1">
<img class="img2">
<img class="img3">
<img class="img4">
<img class="img5">
</div>
</div>
But this is the result that I need -
<div class="gallery-sub-slider">
<div>
<img class="img1">
<img class="img2">
</div>
<div>
<img class="img3">
<img class="img4">
</div>
<div>
<img class="img5">
<img class="img6">
</div>
</div>
$.each(data.carImages, function(i){
counter++;
imgLink = data.carImages[i].imgLink;
console.log(counter);
$('.gallery-slider').append('<div><img src="' + imgLink + '" class="gallery-img" data-tag="' + i + '"></div>');
$('.gallery-sub-slider').append('<div class="sub-gallery-item" data-index="' + i + '"></div>');
$('.gallery-sub-slider div').append('<img src="' + imgLink + '" class="sub-gallery-img" data-tag="1"><img src="' + imgLink + '" class="sub-gallery-img">');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Rather than looping through each data.carImage, you can consider first calculating the number of divs you will require:
var divCount = Math.ceil(data.carImages.length / 2)
And loop through those:
for (var i = 0; i < divCount; i++) {
var firstImgIndex = i*2;
var secondImgIndex = firstImgIndex + 1;
var firstImg = data.carImages[firstImgIndex];
var secondImg = data.carImages[secondImgIndex];
// create your div now, with your first and second img, but you might have to check that secondImg !== null or undefined
}
Related
I'm trying to transform div content from img to div strong
for example
<div class="multi-gallery-image show" id="service_preview">
<img alt="image" src="チャイルドカット¥3000">
<img alt="image" src="ジュニアカット">
<img alt="image" src="ハナコカット">
<img alt="image" src="Hair Styling">
<img alt="image" src="Manicures">
<img alt="image" src="Hair Coloring">
</div>
I want to transform to div strong
<div class="multi-gallery-image show" id="service_preview">
<div><strong>チャイルドカット¥3000</strong></div>
<div><strong>ジュニアカット</strong></div>
<div><strong>トップスタイリストカット</strong></div>
<div><strong>Hair Styling</strong></div>
<div><strong>Manicures</strong></div>
<div><strong>Hair Coloring</strong></div>
</div>
I have this but the result is different as expected:
let servicePreview = document.getElementById('service_preview'); //parent where I am trying to introduce the src values
let myImg;
let mySrc;
let toPush;
if (servicePreview.getElementsByTagName('img').length > 0){
let servicesNumber = servicePreview.getElementsByTagName('img').length; //number of img tags inside the service_preview
for (let i = 0; i < servicesNumber; i++){
myImg = servicePreview.getElementsByTagName('img')[i]; //capturing the img tag
mySrc = myImg.getAttribute('src'); //capturing the src value from img tag
toPush = '<div><strong>' + mySrc + '</strong></div>'; //creating html tag for push to the parent service_preview
servicePreview.append(toPush); //appending the html tag
}
}
but the result of this is
<div class="multi-gallery-image show" id="service_preview">
<img alt="image" src="チャイルドカット¥3000">
<img alt="image" src="ジュニアカット">
<img alt="image" src="ハナコカット">
<img alt="image" src="トップスタイリストカット">
<img alt="image" src="Hair Styling">
<img alt="image" src="Manicures">
"<div><strong>チャイルドカット¥3000</strong></div>"
"<div><strong>ジュニアカット</strong></div>"
"<div><strong>ハナコカット</strong></div>"
"<div><strong>トップスタイリストカット</strong></div>"
"<div><strong>Hair Styling</strong></div>"
"<div><strong>Manicures</strong></div>"
</div>
I want to delete that "quotes" on every div strong, that is a string.
I have to delete the complete img tag after solve the "quotes"
problem
use createElement to create dom element to appendChild and removeChild to remove elements.
let servicePreview = document.getElementById('service_preview');
var myImg;
var mySrc;
let toPush;
var elements = servicePreview.getElementsByTagName('img');
while (elements[0]) {
newDiv = document.createElement('div');
newStrong = document.createElement('strong');
newStrong.innerHTML = elements[0].getAttribute('src');
newDiv.appendChild(newStrong);
servicePreview.appendChild(newDiv);
elements[0].parentNode.removeChild(elements[0]);
}
<div class="multi-gallery-image show" id="service_preview">
<img alt="image" src="チャイルドカット¥3000">
<img alt="image" src="ジュニアカット">
<img alt="image" src="ハナコカット">
<img alt="image" src="Hair Styling">
<img alt="image" src="Manicures">
<img alt="image" src="Hair Coloring">
</div>
Unlike jQuery append() the native method treats html strings as text
Use insertAdjacentHTML(position, html) instead
const str = '<div class="inserted">Test</div>'
document.getElementById('one').append(str);// shows as text
document.getElementById('two').insertAdjacentHTML('beforeend', str)
.inserted{color:red}
<div id="one"></div>
<div id="two"></div>
In raw JavaScript I believe its something like this.
const services = ['チャイルドカット¥3000', 'ジュニアカット', 'ハナコカット',
'Hair Styling', 'Manicures', 'Hair Coloring']
const preview = document.getElementById("service_preview")
services.forEach(service =>{
const div = document.createElement("div")
const strong = document.createElement("strong")
strong.innerText = service
div.appendChild(strong)
preview.appendChild(div)
})
const servicePreview = document.getElementById("service_preview");
const imageSources = [...servicePreview.children].map((img) => img.src);
console.log(imageSources);
// Remove all images
while (servicePreview.firstChild) {
servicePreview.removeChild(servicePreview.firstChild);
}
// Add new div/strong tags
for (const imageSource of imageSources) {
const div = document.createElement("div");
const strong = document.createElement("strong");
strong.textContent = imageSource;
div.appendChild(strong);
servicePreview.appendChild(div);
}
simply use replaceChild() method
there is a trap with img.src because you get an URI
const servicePreview = document.getElementById('service_preview')
servicePreview.querySelectorAll('img').forEach(imgElm=>
{
let newDiv = document.createElement('div')
, newStrg = document.createElement('strong')
;
newDiv.appendChild( newStrg )
newStrg.textContent = imgElm.getAttribute('src') // or decodeURI( imgElm.src.split('/').pop() )
servicePreview.replaceChild( newDiv, imgElm )
})
<div class="multi-gallery-image show" id="service_preview">
<img alt="image" src="チャイルドカット¥3000">
<img alt="image" src="ジュニアカット">
<img alt="image" src="ハナコカット">
<img alt="image" src="Hair Styling">
<img alt="image" src="Manicures">
<img alt="image" src="Hair Coloring">
</div>
I have working javascript code that produces multiple random images in to one div.
I have tried a few attempts to display each random image in a separate div but with no luck. I got "close" but no success.
Here is working code:
<head>
<style>
.onetwothreefour {
width: 25%;
display: inline-block;
}
</style>
<script>
function displayNow() {
var images = ["00.png","01.png","02.png","03.png","04.png","05.png","06.png"];
var selectedIndices = []
while (selectedIndices.length < 4) {
var index = images[Math.floor(Math.random() * images.length)]
if (selectedIndices.indexOf(index) == -1) {
selectedIndices.push(index)
}
}
for (i = 0; i < selectedIndices.length; i++) {
var img = document.createElement("img");
img.src = "imagesfolder/" + selectedIndices[i]
img.className = "onetwothreefour"
var src = document.getElementById("images");
src.appendChild(img);
}
}
</script>
</head>
<body onLoad="displayNow();">
<div id="images"><!-- Images --></div>
<!-- the above works fine but I would like the result below -->
<div class="container"><div class="row">
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
</div></div>
</body>
Note: I have jquery and bootstrap loaded.
I appreciate any help.
Explaination : The while loop runs for four times. A random index is generated, and the element is removed from images array, and pushed into selectedIndices array. By this way, no iteration will be wasted, as each time, a unique image will be generated. I have used forEach loop, which iterates over all the elements of selectedIndices array.
NOTE : The comment inside the forEach loop is a one line way to do so. However, using innerHTML is not appreciated sometimes.
function displayNow() {
var images = ["00.png", "01.png", "02.png", "03.png", "04.png", "05.png", "06.png"];
var selectedIndices = [];
var src = document.getElementById("images");
while (selectedIndices.length < 4) {
let index = Math.floor(Math.random() * images.length);
let img = images.splice(index, 1)[0];
selectedIndices.push(img)
}
selectedIndices.forEach((el) => {
let img = new Image();
img.src = "imagesfolder/" + el;
img.alt = el;
img.className = "onetwothreefour";
let imgCont = document.createElement("div");
imgCont.append(img);
src.append(imgCont);
// src.innerHTML += "<div><img class='onetwothreefour' src='imagesfolder/" + el + "' alt='" + el + "'></div>";
});
}
.onetwothreefour {
width: 25%;
display: inline-block;
}
<body onLoad="displayNow();">
<div id="images"></div>
<div class="container">
<div class="row">
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
</div>
</div>
</body>
You're already using createElement() to build the img elements - you can use the same method to create a new div, add the child img to it, then append that to the DOM. Try this:
function displayNow() {
var src = document.getElementById("images");
var images = ["00.png", "01.png", "02.png", "03.png", "04.png", "05.png", "06.png"];
var selectedIndices = []
while (selectedIndices.length < 4) {
var index = images[Math.floor(Math.random() * images.length)]
if (selectedIndices.indexOf(index) == -1) {
selectedIndices.push(index)
}
}
for (i = 0; i < selectedIndices.length; i++) {
var img = document.createElement("img");
img.src = "imagesfolder/" + selectedIndices[i]
img.className = "onetwothreefour";
img.title = selectedIndices[i]; // just for this demo
var div = document.createElement('div');
div.append(img);
src.append(div);
}
}
.onetwothreefour {
width: 25%;
display: inline-block;
}
<body onLoad="displayNow();">
<div id="images">
<!-- Images -->
</div>
<!-- the above works fine but I would like the result below -->
<div class="container">
<div class="row">
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
</div>
</div>
</body>
I have six boxes. In this box already have dummy image.I need to upload image and that placed to the top box one by one and need to delete also.
When we upload image using upload button, that placed on above div one by one. Currently when i try to add image that placed to all the six divs.
<div class="image-wrapper" style="display:flex;">
<div class="image-wrap">
<img id="img_0" src="assets/images/img1.jpg" class="img-fluid">
</div>
<div class="image-wrap">
<img id="img_1" src="assets/images/unloaded-img.png" class="img-fluid">
</div>
<div class="image-wrap">
<img id="img_2" src="assets/images/unloaded-img.png" class="img-fluid">
</div>
<div class="image-wrap">
<img id="img_3" src="assets/images/unloaded-img.png" class="img-fluid">
</div>
<div class="image-wrap">
<img id="img_4" src="assets/images/unloaded-img.png" class="img-fluid">
</div>
<div class="image-wrap">
<img id="img_5" src="assets/images/unloaded-img.png" class="img-fluid">
</div>
</div>
<div class="upload-btn">
<div class="upload-btn-wrapper">
<button class="btn">Upload a file1</button>
<input type="file" id="files" name="files[]" multiple="">
</div>
</div>
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<div><span class=\"pip image-wrap\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">X</span>" +
"</span></div>").insertAfter(".image-wrap");
$(".remove").click(function(){
$(this).parent(".pip").remove();
});
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
You are using generic selector (".image-wrap") hence image getting added to all div. You can access divs with index 0... n using eq() method and maintain last index in a variable so that you can calculate next index and add next image to the div.
No need to add remove button click handler each time when file loaded as this will cause issue and you will end with multiple click handler. Better, put it outside using .on() so that dynamically added remove buttons will work.
See below code
$(document).ready(function() {
var imageIndex = 0; // variable to save index
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<div><span class=\"pip image-wrap\">" +
"<img class=\"imageThumb\" src=\"" + e.target.result
+ "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">X</span>" +
"</span></div>").insertAfter(".image-wrap:eq(" + imageIndex + ")"); // use index
imageIndex++; // increment index by 1
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
// put remove action here for dynamically added image
$(document).on("click",".remove",function(){
$(this).parent(".pip").remove();
});
});
Just because you are using a class selector with insertAfter its adding the image after every div having class .image-wrap instead use below code. Use the last() function to get the last .image-wrap and append it to that element. Below is a sample code.
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#files").on("change", function(e) {
});
} else {
alert("Your browser doesn't support to File API")
}
});
function uploadFile() {
var files = $('#files')[0].files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
var emptyImg = $('img.img-fluid:not(.hasImage)');
emptyImg[0].src = e.target.result;
$(emptyImg[0]).addClass('hasImage');
$(".remove").click(function() {
var img = $(this).parent().find('img.hasImage')[0];
img.src = '';
$(img).removeClass('hasImage');
});
});
fileReader.readAsDataURL(f);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="image-wrapper" style="display:flex;">
<div class="image-wrap">
<img width="100" id="img_0" src="assets/images/img1.jpg" class="img-fluid">
<span class="remove">X</span>
</div>
<div class="image-wrap">
<img width="100" id="img_1" src="assets/images/unloaded-img.png" class="img-fluid">
<span class="remove">X</span>
</div>
<div class="image-wrap">
<img width="100" id="img_2" src="assets/images/unloaded-img.png" class="img-fluid">
<span class="remove">X</span>
</div>
<div class="image-wrap">
<img width="100" id="img_3" src="assets/images/unloaded-img.png" class="img-fluid">
<span class="remove">X</span>
</div>
<div class="image-wrap">
<img width="100" id="img_4" src="assets/images/unloaded-img.png" class="img-fluid">
<span class="remove">X</span>
</div>
<div class="image-wrap">
<img width="100" id="img_5" src="assets/images/unloaded-img.png" class="img-fluid">
<span class="remove">X</span>
</div>
</div>
<div class="upload-btn">
<div class="upload-btn-wrapper">
<button class="btn" onclick="uploadFile()">Upload a file1</button>
<input type="file" id="files" name="files[]" multiple="">
</div>
</div>
Hope this helps :)
I have 3 images. What i want to do is when i click on any one of the image a random image should be displayed on a div.
Here is the code. Help please.
var iarr=["1.jpg","2.jpg","3.jpg"];
function select()
{
var random=Math.floor(Math.Random()*3);
document.getElementById('disp').innerHTML = iarr[random];
}
<html>
<body>
<h4> MAKE A CHOICE </h3>
<img id='x' onclick="select" src='1.jpg'/>
<img id='y' onclick="select" src='2.jpg'/>
<img id='z' onclick="select" src='3.jpg'/>
<div id='disp'/>
var iarr=["1.jpg","2.jpg","3.jpg"];
function select(){
var random = Math.floor(Math.random() * iarr.length);
var div = document.getElementById('disp');
var image = "<img src=\"" + iarr[random] + "\"/>";
div.innerHTML = image;
}
<html>
<body>
<h4> MAKE A CHOICE </h4>
<img id='x' onclick="select()" src='1.jpg'/>
<img id='y' onclick="select()" src='2.jpg'/>
<img id='z' onclick="select()" src='3.jpg'/>
<div id='disp'/>
Working example: https://jsfiddle.net/pndtdt7t/
var iarr = [
"http://www.wallpapers-for-desktop.com/desktopbilder_for_free/free_desktopbild.jpg",
"http://wikiin.com/media/images/15/04/21/cfe0fdfb23.jpg",
"http://data.whicdn.com/images/89382997/large.jpg"
];
function select() {
var img = "<img src=\""+iarr[Math.floor(Math.random() * iarr.length)]+ "\" />";
document.getElementById('disp').innerHTML = img;
}
<html>
<body>
<h4> MAKE A CHOICE </h3>
<img id='x' onclick="select()" src='1.jpg'/>
<img id='y' onclick="select()" src='2.jpg'/>
<img id='z' onclick="select()" src='3.jpg'/>
<div id='disp'/>
I've created a webpage with many (over 100) paired flash cards with Question (image) flipping to Answer (image) when clicked. If possible I would like to be able to randomise the order in which the question/answer pairs load with each page load/refresh.
<div class="content4Column gap">
<div class="card-container">
<div class="card click" data-direction="left">
<div class="front">
<img src="Intermolecular/Q1.png" width="100%" height="100%" alt="">
</div>
<div class="back">
<img src="Intermolecular/A1.png" width="100%" height="100%" alt="">
</div></div></div></div>
Try
var QAPairs = [];
var QATotal = 200; // total numbers of QA pairs
var QA = 20; //number of QA pairs you want. Set to QATotal to include all QA pairs
while(QAPairs.length != QA){
var rand = Math.floor(Math.random()*QATotal);
if(QAPairs.indexOf(rand) == -1){
QAPairs.push(rand);
// If you want to show them all at a time
document.getElementsByClassName("card click")[0].innerHTML = document.getElementsByClassName("card click")[0].innerHTML + '<div class="front">\
<img src="Intermolecular/Q' + QAPairs[i] + '.png" width="100%" height="100%" alt="" />\
</div>\
<div class="back">\
<img src="Intermolecular/A' + QAPairs[i] + '.png" width="100%" height="100%" alt="" />\
</div>';
}
}
// if you want to show them one at a time
var i = 0;
function updateCard(){
document.getElementsByClassName("card click")[0].innerHTML = '<div class="front">\
<img src="Intermolecular/Q' + QAPairs[i] + '.png" width="100%" height="100%" alt="" />\
</div>\
<div class="back">\
<img src="Intermolecular/A' + QAPairs[i] + '.png" width="100%" height="100%" alt="" />\
</div>';
i++;
}