Passing an array of Images from JS file to EJS - javascript

Hi I am trying to pass an array of image src's from my javascript file to my ejs file below.
<div id = "flick">
<img src="nothing.jpg" id="image" name="image"/>
<% var imgArray = imgLinks %> //Grab the array of img src's
<script>
var passArray = [];
passArray = <%= imgArray %>; // Pass to a local array
for (i = 0; i < passArray.length; i++){
document.getElementById('image').src = passArray[i];
}
</script>
</div>
I have tested and found that i am receiving the array 'imgLinks' correctly , but i would like to know how i could pass and display all the array of images. I am new to Javascript sorry if this is dumb.

You keep overwriting the same image tag with an image until you are at the end of the array.
What you could do is to clone the image tag and then add it as child to the "flick" div
var passArray = [];
passArray = <%= imgArray %>; // Pass to a local array
for (i = 0; i < passArray.length; i++){
var itm = document.getElementById('image');
var cpy = itm.cloneNode(true);
cpy.id = "image" + i;
cpy.src = passArray[i];
document.getElementById("flick").appendChild(cpy);
}
This will generate a copy of top most image and append it to the flick div. If you need to remove the original img tag you can execute:
document.getElementById("image").remove()
after the for loop.
See a working fiddle here: https://jsfiddle.net/0Lsh2y1j/2/

Related

Get all image src from array of image src and placing them into div with Javascript?

I have I array of images src ["http://src1", "http://src2", "http://src3"]. I want for get all images from that array and manipulate them, for example placing them into a div?
var imgSrc = ["http://src1,http://src2,http://src3"];
var string = imgSrc[0];
console.log(string);
var array = string.split(",");
console.log(array);
var inHTML = '';
console.log(array[0]);
$.each(array, function(key, value){
var html = '<img src="'+ value[key]+'" align="center">';
inHTML += html;
});
$('div#item').html(inHTML);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="item"></div>
You can append the dynamically created Images from the array to a perticular div. Hope this helps...
HTML
<html>
<head>
</head>
<body>
<h1>Images</h1>
<div id="content">
</div>
<script src="app.js"></script>
</body>
</html>
JS
var imageSources = ["http://src1,http://src2,http://src3"]
imageSources.forEach(element => {
var img = document.createElement("img");
img.width = '300';
img.height = '300';
img.src = element;
document.getElementById("content").appendChild(img)
};
I think your array is somewhat like:
["http://src1","http://src2","http://src3"]
If I am right then you can do something like:
var y = x.map((key,value)=>{return ('<div>'+key+'</div>')});
y will be an array with the div tags containing images.
Hope, I understood your problem.
I want for get all images from that array and manipulate them, for
example placing them into a div
You can dynamically generate img elements and add them to a div.
To iterate through the array you could use forEach, creating the img elements within the loop using createElement and appendChild to append the image to the div
See example below, which should get you started.
var images = ["https://placehold.it/50x50","https://placehold.it/25x25","https://placehold.it/75x75"];
var target = document.getElementById('target');
images.forEach(function(imgSrc){
var newImg = document.createElement("img");
newImg.src = imgSrc;
target.appendChild(newImg);
})
<div id="target"></div>
Creating an Array:
You must use the following syntax to to create a JavaScript Array:
var array_name = [ item1, item2, ... ];
Or Using the JavaScript Keyword new:
var array_name = new Array( item1, item2, ... );
So your array must be like this:
var image_source = [ 'http://src1', 'http://src2', 'http://src3' ];
Access the Elements of an Array:
You refer to an array element by referring to the index number. for example this statement accesses the value of the first element in cars:
var first_image = image_source[ 0 ];
Example:
var image_source = [ 'http://img1', 'http://img2', 'http://img3' ];
document.getElementById( 'demo' ).innerHTML = image_source[ 1 ];
<div id="demo"></div>

Get value from a JSON file with multi dimensional array using jQuery $.getJSON method

I've been trying to fetch some values from a JSON file using the $.getJSON method. The first two loops are static so I wrote the below code to fetch the value of "layers.name". From the third loop, the data in the layers may or may not be available. How can I fetch the value of all "layers.name"presented in the JSON file
PS: The JSON file is an output generated from a software where the layer is presented
in this format
Here the code I've worked so far where I get the first two loop layers.
Html
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="test.js"></script>
</body>
Javscript
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
var layer = data.layers.reverse()
for (i=0; i<layer.length; i ++){
name = data.layers[i].name
id= data.layers[i].do_objectID
var className = '.'+id
var main = "<div class=\""+id+"\" data-number=\""+i+"\">"+name+"<\/div>"
$('body').append(main);
var subLayer = data.layers[i].layers.reverse()
for(j=0; j<subLayer.length; j++){
newname = data.layers[i].layers[j].name
$().append(' '+newname);
var subsubLayer = data.layers[i].layers[j]
var sub = "<div class=\""+newname+"\" data-number=\""+j+"\">"+newname+"<\/div>"
$(className).append(sub);
}
}
})
Thanks
Link to Fiddle
I think it's a good idea use recursion. Here is example:
var container = document.getElementById("container");
$.getJSON('https://api.myjson.com/bins/6atbz', function(data) {
buildTree(data, container)
})
function buildTree (node, container) {
var layers = node.layers || [];
console.info(node);
layers.forEach(function(item) {
var newContainer = document.createElement('div');
var span = document.createElement('span');
span.innerHTML = item.name;
newContainer.appendChild(span);
container.appendChild(newContainer);
if(item.layers){
buildTree(item, newContainer)
}
});
}
Here is live demo

Get image names in html using JavaScript

How can I pick up image name in html using JavaScript? I searched google and there are some documents about how to get image name on <img> tag,
var filename = tag.replace( /^.*?([^\/]+)\..+?$/, '$1' );
But it return just one name of images. What I'm going to do is get all images name. Imagine the html below,
<html>
<body>
<div class="imagebox">
<img src="/some/path/imageOne.jpg">
<img src="/some/path/imageTwo.jpg">
<img src="/some/path/imageThree.jpg">
</div>
</body>
</html>
after magic, return
imageOne, imageTwo, imageThree. How can I do this..?
Add the following Javascript code at the bottom of your html page :
Solution for browser environment :
var images = document.getElementsByTagName('img');
var images_urls = [];
var images_names = [];
var tmp;
for(var i=0;i < images.length;i++){
images_urls[i] = images[i].getAttribute('src');
tmp = images[i].getAttribute('src').split('/');
images_names[i] = tmp[tmp.length -1].split['.'][0];
}
console.log(images_names); // ["imageOne", "imageTwo", "imageThree"]
and now images_names is an array containing the image names, in this case imageOne,imageTwo and imageThree
Solution for Node.js environment:
lets say you have images url stored in images variable like this :
var images = ["/some/path/imageOne.jpg", "/some/path/imageTwo.jpg", "/some/path/imageThree.jpg"];
you can use Regex, but in this case you can do it easily without using Regex, just split each image url and grab the last part of it, pretty simple, something like this :
var images_names = [];
var tmp
for(var i=0;i < images.length;i++){
tmp = images[i].split('/');
images_names[i] = tmp[tmp.length -1].split['.'][0];
}
console.log(images_names); // ["imageOne", "imageTwo", "imageThree"]
It is the same solution for both Browser and Node.js environment except for the way you get the elements.
Hope this helps.

getElementById() .innerHTML/.src

I'm trying to create a simple javascript game for college and am having trouble getting what i want to display on screen.
my script is as follows:
var qArray = new Array();
qArray[0] = {image:"Images/q1.png"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray.splice(count,1);
when i use this i get "undefined":
document.getElementById("question").innerHTML = question.image;
and when i use this i get nothing:
document.getElementById("question").src = question.image;
my html is just a simple div like so:
<div id = "question" align = "center">
</div>
i need to have the "count" variable because it increments to show the next image for the next question
if anyone could help that would be great
Here is a working Fiddle. qArray.splice() doesn't work because it actually removes that element from the array and returns a new array while you were just looking for a specific index in the array (not to mention you just deleted the element you were looking for)
This works. I used a random imgur image to show that it does indeed load.
<html><head></head><body>
<img src="" id="question"></img>
<script type="text/javascript">
var qArray = new Array();
qArray[0] = {image:"http://i.imgur.com/pGpmq.jpg"};
qArray[1] = {image:"Images/q2.png"};
qArray[2] = {image:"Images/q3.png"};
qArray[3] = {image:"Images/q4.png"};
qArray[4] = {image:"Images/q5.png"};
var count = 0;
var question = qArray[count];
document.getElementById('question').src = question.image;
</script>
</body>
</html>

How to display images using Javascript and JSON

I have to display images to the browser and I want to get the image from a JSON response and display it to the browser using Javascript. This is what the JSON response looks like:
[{
"0":"101",
"member_id":"101",
"1":"3k.png",
"image_nm":"3k.png",
"2":"\/images\/phones\/",
"image_path":"\/images\/"
},{
"0":"102",
"member_id":"102",
"1":"mirchi.png",
"image_nm":"mirchi.png",
"2":"images\/phones\/",
"image_path":"images\/phones\/"
},{
"0":"103",
"member_id":"103",
"1":"masti.png",
"image_nm":"masti.png",
"2":"images\/phones\/",
"image_path":"images\/phones\/"
}]
How do I do this (I am a beginner)?
here is the code what i wrote...
var jsonString = '[{"0":"101","member_id":"101","1":"3k.png","image_nm":"3k.png","2":"\/images\/phones\/","image_path":"\/images\/phones\/"},{"0":"102","member_id":"102","1":"mirchi.png","image_nm":"mirchi.png","2":"images\/phones\/","image_path":"images\/phones\/"},{"0":"103","member_id":"103","1":"masti.png","image_nm":"masti.png","2":"images\/phones\/","image_path":"images\/phones\/"}]';
var obj = JSON.parse(jsonString);
for(var i = 0, len = obj.length; i < len; i++){
var img = new Image();
img.setAttribute("src",obj[i][2] + obj[i][1]);
document.body.appendChild(img);
}
Assuming you parsed your json in a variable called json, this would add all images in a container with id yourcontainer:
var images = '';
for( var i=0, max<json.length; ++i ) {
images += '<img src="' + json[i]['image_path'] + json[i]['image_nm'] + '" />';
}
document.getElementById( 'yourcontainer' ).innerHTML = images;
Seems pretty straight forward. If this is json_encoded, then we can use json[key] to get the value, if you aren't familiar with the term 'key', json encodes arrays in the key:value, format, so for this, if we used json[member_id], we would get '101', if we used json[image_nm], we would get '3k.png', putting this all together it seems as if it's pretty well separated, you just have to know what goes where. I have an idea, but not 100%,I would expect you to do something like
var myImages = '';
for(var i = 0; i < json.length; i++){
myImages += '<img src="'+json[i]['image_path']+json[i]['img_nm']+'" />';
}
document.getElementById('myImgHolder').innerHTML = myImages;
Based on your json data, this would evaluate a variable and test it against the length of the json array. The statement also declares that while the variable is less than the total length of the json array, we will iterate to the next object. We would expect output along the format of -
<img src="/images/3k.png" />.
Then it would take the new images and place them in a Div with the id of myImgHolder.
Hope this helps.
EDIT 1
If you don't have a container to place these images inside of it, then you will need to create the container and place it somewhere.
var myImgHolder = document.createElement('div');
myImgHolder.setAttribute("id", "myImgHolder");
document.getElementById('ICanTargetThis').appendChild(myImgHolder);
The above code sets the variable myImgHolder to the creation of a new DIV element. Then, using the variable, we declare the attribute "id" to set as 'myImgHolder'. Now we have the element. But what do we do with it? Well we MUST target an existing element within our page, even if we're just targeting the tag...something. then we use the .appendChild method and use our variable...appendChild(myImgHolder);
You can use jQuery here.
Add following script in the head tag.
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).ready(function () {
var url = "entries.json";
$.getJSON(url, function (url){
var img= "";
$.each(url, function () {
img += '<li><img src= "' + this.images+ '"></li>';
});
$('body').append(img);
});
});
</script>

Categories