How do I get full image source (like "http://lorempixel.com/400/200/sports/1") by concatenation of partial source:
var url = "http://lorempixel.com/400/200/sports/"
and numbers from array
var arr = [1,2,3,4,5];
I already have list of images
<ul id="imageList"></ul>
I want to append images like this
for (var i = 0; i < arr.length; i++) {
$('#imageList').append('<li><img class="imageClass" src = "url + 'arr[i]'" /></li>');
}
Here source concat. is not working
This is because you did not use url and arr[i] as a variable by closing the string before concatenating the variables with a +.
.append('<li><img class="imageClass" src="' + url + arr[i] + '" /></li>');
If you have a text editor that highlights your code for you, url and arr[i] should be in a different colour.
Demo: http://jsfiddle.net/WLv6F/
You can set the src of the image using JavaScript:
var arr = [1,2,3,4,5];
var url = "http://lorempixel.com/400/200/sports/" + arr[0];
var img = document.createElement('img');
img.className = 'imageClass';
img.src = url;
By looping through your array elements, you can append them to your list. Here I show two methods of looping: Array.prototype.forEach and also a for loop if that's what you prefer:
var url = "http://lorempixel.com/400/200/sports/";
var arr = [1, 2, 3, 4, 5], img, listItem;
// Using foreach
arr.forEach(function(id) {
listItem = document.createElement('li');
img = document.createElement('img');
img.className = 'imageClass';
img.src = url + id;
listItem.appendChild(img);
document.getElementById('imageList').appendChild(listItem);
});
// Using for
for (var i = 0; i < arr.length; ++i) {
listItem = document.createElement('li');
img = document.createElement('img');
img.className = 'imageClass';
img.src = url + arr[i];
listItem.appendChild(img);
document.getElementById('imageList').appendChild(listItem);
}
"src = '" + url + arr[0] + "'/>"
Edit:
He has it wrong with:
'<li><img class="imageClass" src = "url + 'arr[i]'" /></li>'
It should be:
'<li><img class="imageClass" src = "' + url + arr[i] + '" /></li>'
Related
I have generated multiple barcodes using this code:
function getCode() {
var multipleCodes = document.getElementById('codeArea').value;
var eachLine = multipleCodes.split('\n');
console.log("eachLine = " + eachLine);
for (var i = 0; i < eachLine.length; i++) {
console.log("Inside loop: " + eachLine[i]);
var div = document.createElement('iframe');
div.innerHTML = "";
div.setAttribute('id', 'iFrameID' + i);
document.body.appendChild(div);
document.getElementById('iFrameID' + i).src = 'barCodeGenerator/generateBarCode.php?q=' + eachLine[i];
}
and trying to print it by using this method:
function printDiv(divName) {
var strName = document.getElementById("codeArea").value;
var imageId = document.getElementsByClassName('decoded');
var imagObject = new Image();
imagObject = imageId;
var originalImage = '<img id="imageViewer" src="' + imageSrc + '" style="padding-top: 20px" alt="' + imageSrc + '" />';
popup = window.open('', 'popup', 'toolbar=no,menubar=no,width=700,height=650');
popup.document.open();
popup.document.write("<html><head></head><body onload='print()'>");
popup.document.write(originalImage);
popup.document.write("</body></html>");
window.close('popup');
popup.document.close();
setTimeout(function () { popup.close(); }, 8000);
}
which only print single image by merging all barcodes.
How can i print them separately as multiple images.
Any help will be appreciated.
The most part of this code is irrelevant to your question. Consider removing your logs, the parts about showing popup and hiding it for more clearance.
Seems imageSrc variable in your code contains the source of one image, so you need to change your code by sending the array of image sources and iterating over it:
var originalImage = '';
// assuming imageSrc is an array of image sources
for (var i=; i < imageSrc.length; i++) {
// note that I'm changing the id of the image a litle bit to ensure it will remain unique
originalImage += '<img id="imageViewer' + i + '" src="' + imageSrc[i] + '" style="padding-top: 20px" alt="' + imageSrc[i] + '" />';
}
then the rest of your code must work.
I have a folder with images that have long filenames, but they all have unique product ID numbers at the beginning
e.g. 1023-Very-Long-Image-Name.jpg.
What I'm trying to do is to get full image filename into my javascript, by just using this unique ID number.
e.g. I need to find an image with ID 1023, which is this one - 1023-Very-Long-Image-Name.jpg
All unique IDs stored in JSON database. So below is an example of my code:
$('.choose-range-cta').click(function () {
var rowID = $(this).attr("id");
var stylesTable = JSON.parse(stylesDB);
var styleHTML = "";
for (var i = 0; i < stylesTable.length; i++) {
if (stylesTable[i].collectionID == rowID) {
var blockTitle = stylesTable[i].styleName;
var blockPrice = stylesTable[i].fromPrice;
var blockSize = stylesTable[i].size;
var blockImageID = stylesTable[i].frontImageID;
styleHTML += "<div class=\"col-lg-4 style-block\"><span class=\"style-name\">" + blockTitle + "</span><span class=\"from-price\">from £" + blockPrice + "</span><span class=\"cta\">Select</span><div class=\"img-box\"><img src=\"" + ImagePath + blockImageID +"\"></div><span class=\"copy\">" + blockSize + "</span></div>";
}
}
$('#style-list').html(styleHTML);
});
Assuming your list is an array, use filter:
var imageArray = [
'1021-Don-Long-Image-Name.jpg',
'1022-Very-Long-Image-Name.jpg',
'1023-Dan-Long-Image-Name.jpg',
'1024-BobLong-Image-Name.jpg'
];
function getName(data, id) {
return data.filter(function (el) {
return el.substring(0, 4) === id;
})[0];
}
var name = getName(imageArray, '1023'); // 1023-Dan-Long-Image-Name.jpg
DEMO
I have a two-dimensional array (affiliates) where each array item consists of an image URL and a link URL. randArray is simply a generated list of random numbers (non-repeating) that matches the length of affiliates.
I've gotten to the point where I can successfully generate an HTML string for randomized image/url combinations.
(The above might be more information than needed but I wanted to provide a little background.)
What I'm trying to do is group every three iterations together and wrap in <p> tags. I've tried doing a nested loop inside the current one but could only get to where it was wrapping three of the same line in a <p> tag, whereas I need them to be three successive lines. I feel like this should be pretty easy, but I'm stumped. Any help would be much appreciated.
for(var y=0; y < randArray.length; y++) {
var image = affiliates[randArray[y]][0];
var url = affiliates[randArray[y]][1];
var fullString = '<img src="' + image + '">';
console.log(fullString);
}
WIthin your loop, y % 3 == 0 will be true on the first iteration and every third after it, so output your <p> when y % 3 == 0 and your </p> when y % 3 == 2 and after your loop if length % 3 != 0.
But a nested loop is probably easier to do and maintain:
var x, image, url;
var fullString = "";
var y = 0;
while (y < randArray.length) {
fullString += '<p>';
for (x = 0; x < 3 && y < randArray.length; ++x, ++y) {
image = affiliates[randArray[y]][0];
url = affiliates[randArray[y]][1];
fullString += '<img src="' + image + '">';
}
fullString += '</p>';
}
for(var y=0; y < randArray.length; y++) {
var image = affiliates[randArray[y]][0];
var url = affiliates[randArray[y]][1];
var fullString = '';
if(y%3 == 2){
fullString += '<p>';
}
fullString = '<img src="' + image + '">';
if(y%3 == 2){
fullString += '</p>';
}
console.log(fullString);
}
I am not sure if I understand, but...
var t = [];
for(var i=0;i<affiliates.length;i++) t.push(i);
while(t.length>2){
var str = '';
for(var i=0;i<3;i++){
str += '<a href="';
var r = Math.floor(Math.random()*t.length);
str += affiliates[t[r]][1] + '"><img src="';
str += affiliates[t[r]][0] + '"></a>';
t.splice(r,1);
}
str = '<p>'+str+'</p>';
console.log(str);
}
I would do something like this, but it's not optimized code, sorry :/
var counter = 1; //external counter for module (%3)
var open = false;
var tagOpen = '<p>';
var tagClose = '</p>';
var fullstring = '';
var buffer = ''
for(var y=0; y < randArray.length; y++) {
var image = affiliates[randArray[y]][0];
var url = affiliates[randArray[y]][1];
//groups entries
buffer += '<img src="' + image + '">';
if(counter % 3 == 0){
fullstring = tagOpen + buffer + tagClose; //concat strings
console.log(fullString);
open = false; //set open to false
} else {
open = true;
}
counter++;
}
//if at the end of the loop there's still an open tag, close it
if(open){
fullstring += tagClose;
}
I figured adding &outputSelector=GalleryInfo to the url would provide a higher resolution thumbnail, but that doesn't seem to work. I'm new to JSON, and the tutorial isn't very clear on the exact syntax to add to the URL to make this happen. Thanks!
<script>
function _cb_findItemsByKeywords(root)
{
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
if (null != title && null != viewitem)
{
html.push(
'<tr id="api_microposts"><td>'
+ '<img src="' + pic + '" border="0" width="190">' + '<a href="' + viewitem + '" target="_blank">' + title +
'</a></td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("api").innerHTML = html.join("");
// Define global variable for the URL filter
var urlfilter = "";
// Generates an indexed URL snippet from the array of item filters
function buildURLArray() {
// Iterate through each filter in the array
for(var i=0; i<filterarray.length; i++) {
//Index each item filter in filterarray
var itemfilter = filterarray[i];
// Iterate through each parameter in each item filter
for(var index in itemfilter) {
// Check to see if the parameter has a value (some don't)
if (itemfilter[index] !== "") {
if (itemfilter[index] instanceof Array) {
for(var r=0; r<itemfilter[index].length; r++) {
var value = itemfilter[index][r];
urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value ;
}
}
else {
urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
}
}
}
}
} // End buildURLArray() function
// Execute the function to build the URL filter
buildURLArray(filterarray);
url += urlfilter;
}
</script>
<!--
Use the value of your appid for the appid parameter below.
-->
<script src=http://svcs.ebay.com/services/search/FindingService/v1?SECURITY-APPNAME=*APP ID GOES HERE*&OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.12.0&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&sortOrder=PricePlusShippingLowest&paginationInput.entriesPerPage=6&outputSelector=GalleryInfo&outputSelector=AspectHistogram&itemFilter(0).name=Condition&itemFilter(0).value(0)=New&itemFilter(1).name=MaxPrice&itemFilter(1).value=450.00&itemFilter(1).paramName=Currency&itemFilter(1).paramValue=USD&itemFilter(2).name=MinPrice&itemFilter(2).value=350.00&itemFilter(2).paramName=Currency&itemFilter(2).paramValue=USD&itemFilter(3).name=ListingType&itemFilter(3).value=FixedPrice&keywords=Moto%20x%2016gb>
</script>
It seems like you're looking for the galleryPlusPictureURL: http://developer.ebay.com/Devzone/finding/CallRef/types/SearchItem.html#galleryPlusPictureURL
I have a variable that alternates from referencing different images. For example sometimes I have
var imageName = "A.png". I want to set the innerHTML of a div tag to "src=" + imageName + ">" but it doesn't work. When I used alert to get what the innerHTML actually was, I got this <img src="A" .png="">. Why is this happening?
As per request here is my HTML code pertaining to this problem. It's part of a larger body of code which receives an xml file from a servlet. I find it weird that the for loop at the bottom works fine but the img src bit doesn't.
EDIT: I managed to get the innerHTML into the form <img src="/Users/adamsturge991/Desktop/webapp/Ass5/WEB-INF/classes/A.png"> by changing what the servlet wrote (I added the absolute path just to be sure that the file could be found.) However the picture still isn't loading. Odd
function displayResult(req)
{
var doc = req.responseText;
parser=new DOMParser();
xmlDoc=parser.parseFromString(doc,"text/xml");
var imageName = xmlDoc.getElementsByTagName('ImageName').item(0).textContent + ".png";
var comments = xmlDoc.getElementsByTagName('Comment');
var imgDisplay = document.getElementById('ImageDisplay');
var str = "<img src=" + imageName + ">";
alert(str);
imgDisplay.innerHTML = str;
alert(imgDisplay.innerHTML);
str = '';
for (var j = 0; j < comments.length; j++)
{
str = str + "<p>"+ comments.item(j).textContent + "</p>";
}
var commentDisplay = document.getElementById('CommentDisplay');
commentDisplay.innerHTML = str;
}
I found this example useful:
var url = "www.example.com/image.jpg";
var img = new Image();
img.src = url;
document.body.appendChild(img);
You just need to make some tweaks to adjust to your needs
I think this line is wrong:
var str = "<img src=" + imageName + ">";
This will render as:
<img src=A.png>
But this could confuse the browset
It probably should be:
var str = "<img src=\"" + imageName + "\" \/>";
(that is, quote the attribute value, and for good measure, close the tag.)
This renders as:
<img src="A.png" />
Another solution could be to use template literals:
var str = `<img src="${imageName}">`;