How to handle quoting of HTML in JavaScript document.write - javascript

I'm using document.write to take an array of images and I want to add an onclick event handler to each image by looping through this array. I'm having a very hard time figuring out where to put quotes in this JavaScript code:
for (index = 0; index < buildings.length; index++) {
document.write(
"<img onclick='" + setPhoto() +
"' id='" + images[index].id +
"' src='" + images[index].src +
"' width='50' height='50'/>"
);
};
All help is appreciated.

Pretty much no one uses document.write anymore. Read the disclaimer in the docs
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls document.open which will clear the document.
You're better off doing something like this
for (var index = 0, img; index < buildings.length; index++) {
img = document.createElement('img');
img.src = images[index].src;
img.width = 50;
img.height = 50;
img.onclick = setPhoto;
document.body.appendChild(img);
}
This will attach the images to document.body but you could attach them to any other element you wanted

Related

For loop exceeds the limit when using img src

I have an img_urls array which contains 2 image urls.
I use this array to loop img tag and using for loop.
But instead of having 2 images, i have 3 images in my output.
This is my code;
var img_urls = ["http://i.onionstatic.com/avclub/5648/48/16x9/1200.jpg", "https://www.scienceabc.com/wp-content/uploads/2016/05/horse-running.jpg"];
for (i = 0; i < img_urls.length; i++) {
$("div").append(
"<div><img src=' " + img_urls[i] + "'/></div>"
);
}
So, whats is wrong with my code?
JSFIDDLE
When adding the first image you generate a new div.
Then the second image if appended to existing divs.
You should have only one destination div. Add an id to the main div:
<div id="container"></div>
--
var img_urls = ["http://i.onionstatic.com/avclub/5648/48/16x9/1200.jpg", "https://www.scienceabc.com/wp-content/uploads/2016/05/horse-running.jpg"];
for (i = 0; i < img_urls.length; i++) {
$("div#container").append(
"<div><img src=' " + img_urls[i] + "'/></div>"
);
}
You need to use selector i.e. id class in the main div as when the next iteration occurs it contains two div in the body. Check this fiddle
Problem is that you have $("div") as selector. So when you append the first image, you also add new div. So the next image is appended to two divs. Probably you can add id to your div, so
<div id="test"></div>
...
$("#test").append
Reason is you are appending everything inside the loop.
$(function() {
var img_urls = ["url1", "url2"];
var html= ""
for (i = 0; i < img_urls.length; i++) {
html += "<div><img src=' " + img_urls[i] + "'/></div>";
}
$("div").append(html);
});
You are appending to global div element, you are appending div also, so generated html will append to generated div too.
Here is html,
<div class='test'></div>
Here is javascript code,
$(function() {
var img_urls = ["image_url1", "image_url2"];
var html = '';
for (i = 0; i < img_urls.length; i++) {
html += "<div><img src=' " + img_urls[i] + "'/></div>"
}
$("div.test").append(html);
});
Please find here working link here
I hope this will help
<div id="container"></div>
for (var i = 0; i < img_urls.length; i++) {
console.log(img_urls.length)
$("div#container").append(
"<div><img src=' " + img_urls[i] + "'/></div>"
);
}
when you append the first image you create a div in that div the horse is added and the first div is also populated by the horse
Try this and see Demo
<div></div>
$(function() {
var img_urls = ["http://i.onionstatic.com/avclub/5648/48/16x9/1200.jpg", "https://www.scienceabc.com/wp-content/uploads/2016/05/horse-running.jpg"];
for (i = 0; i < img_urls.length; i++) {
$("div").append(
"<img src=' " + img_urls[i] + "'/> </br>"
);
}
});

AppendChild Javascript

I am trying to append images to a bootstrap column but having no luck, does anyone know what is wrong with my code.
for (i = 0; i <= 11; i++) {
var img = new Image();
img.src = 'http://imagecache.arnoldclark.com/imageserver/" + obfuscatedString + "/" + camera[i] + "';
var row = "<div class='row'><div class='col-md-2'> + img[0] +</div></div>";
document.body.appendChild(row);
}
Any help is appreciated.
Thanks
Sorry, but your code doesn't really make any sense. There are lots of things wrong with it:
Here's what you started with:
for (i = 0; i <= 11; i++) {
var img = new Image();
img.src = 'http://imagecache.arnoldclark.com/imageserver/" + obfuscatedString + "/" + camera[i] + "';
var row = "<div class='row'><div class='col-md-2'> + img[0] +</div></div>";
document.body.appendChild(row);
}
Issues:
You create an <img> DOM object, but don't do anything with it.
You need to pass a DOM object to appendChild() NOT pass a string.
You can't construct a string of HTML by adding img[0] into the string. It simply doesn't work that way at all. You either work entirely in HTML strings or you work in constructed HTML objects or you create an HTML object and then set .innerHTML to a string of HTML. You can't just mix the two the way you are.
I'll take a guess at what you want to do:
for (i = 0; i <= 11; i++) {
var src = "http://imagecache.arnoldclark.com/imageserver/" + obfuscatedString + "/" + camera[i];
var row = document.createElement("div");
row.className = 'row';
row.innerHTML = "<div class='col-md-2'><img src='" + src + "'></div>";
document.body.appendChild(row);
}
This code take the following steps:
Calculate the image src URL.
Create your container div DOM object.
Set the desired className on the container object.
Set the .innerHTML property of the container to the HTML string for the HTML that you want in the container (this will automatically create that set of DOM objects in the container).
Append the container to your document.
Here is an all-javascript solution
var camera = ['http://placehold.it/200x200']
for (i = 0; i <= 0; i++) {
var img = new Image();
img.src = camera[i];
var row = document.createElement('div');
row.className = 'row';
var imgContainer = document.createElement('div');
imgContainer.className = 'col-md-2';
imgContainer.appendChild(img);
row.appendChild(imgContainer);
document.body.appendChild(row);
}
and a jsfiddle demo http://jsfiddle.net/576Tm/1

Using javascript for statement to create a bunch of thumbnail picture links

I want to use javascript to fill a section of a HTML page with thumbnail images that link to the full sized imagaes. Currently all that happens when this code runs is it prints the p open and close. I want it do make the thumbnails for img (#) where # is 1-41.
javascript:
document.getElementById('img').innerHTML = "<p>"
for( var img = 1; img >= 41; img++)
{
document.getElementById('img').innerHTML += ("<a href='img/pic (" + img + ").JPG'><img src='img/thumbs/pic (" + img + ").png' width=156 height=84 alt='img " + img + "'></a>")
}
document.getElementById('img').innerHTML += "</p>"
HTML:
<div class="main">
<div id="img"><div>
</div>
Two things:
Both inside the loop and after it, you're assigning a completely new value to the innerHTML of the element, overwriting anything you might have had in it before. Apparently after the initial post, you edited the question to use += instead. Even so, using innerHTML += ... is a bad idea, as it causes the browser to constantly re-serialize the DOM of the element and re-parse the string each time, and if you hand it half-complete HTML (such as "<p>"), what it uses when you do += may well be "<p></p>" — and so when you add to it, what you add ends up in the wrong place. Instead, build up the text in a variable and then assign it once, at the end.
You're starting with img = 1 and then telling the loop to continue while img >= 41. So the loop body is never run, since 1 is not >= 41.
Minimal update:
var markup = "<p>";
for( var img = 1; img <= 41; img++)
{
markup += "<a href='img/pic (" + img + ").JPG'><img src='img/thumbs/pic (" + img + ").png' width=156 height=84 alt='img " + img + "'></a>";
}
document.getElementById('img').innerHTML = markup + "</p>";
You have an error in for condition section. Replace
for( var img = 1; img >= 41; img++)
with
for( var img = 1; img <= 41; img++)

Javascript for i not printing array

I've searched around and found no pure js solution to my issue that I can apply to my code.
It's a script that prints an array of images, but for now it only prints 1 array.
Pertinent code in html:
<div id="imgViewer"></div>
<script>
var imgViewerImages = ['img/imgViewer/1.png','img/imgViewer/2.png','img/imgViewer/3.png','img/imgViewer/4.png','img/imgViewer/5.png','img/imgViewer/6.png'];
</script>
<script src="services/imgViewer.js"></script>
And in JS:
function imgViewerPrinter(){
var imgViewerTarget = document.getElementById('imgViewer');
imgViewerImages.toString();
for (var i=0;i<imgViewerImages.length;i++){
imgViewerTarget.innerHTML = '<img src="' + imgViewerImages[i] + '">';
}
}
window.onload = imgViewerPrinter();
I'm still a noob is JS so I ask for your pacience.
Thanks in advance
try :
imgViewerTarget.innerHTML += "<img src="' + imgViewerImages[i] + '">";
If you want to print out an array of images shouldnt you have your HTML code in the loop making i the image number for example;
for (var i=0;i<imgViewerImages.length;i++){
var imgViewerImages = ['img/imgViewer/' + [i] + '.png'];
}
Try this optimized soln.
var imgViewerImages =['img/imgViewer/1.png','img/imgViewer/2.png','img/imgViewer/3.png','img/imgViewer/4.png','img/imgViewer/5.png','img/imgViewer/6.png'];
function imgViewerPrinter(){
var imgList=[];
for (var i=0;i<imgViewerImages.length;i++){
imgList.push('<img src="' + imgViewerImages[i] + '" />');
}
var imgViewerTarget = document.getElementById('imgViewer');
imgViewerTarget.innerHTML = imgList.join('');
}
window.onload = imgViewerPrinter();
try something like this,Because your code rewrite innerHTML again and again, so you get last iterated value.
Instead of manipulating DOM in every loop,Below code will manipulate your DOM one time only.
function imgViewerPrinter(){
var imgViewerTarget = document.getElementById('imgViewer');
var imgViewerImages_length = imgViewerImages.length;
var image = '';
for (var i=0;i<imgViewerImages_length;i++){
image += '<img src="' + imgViewerImages[i] + '">';
}
imgViewerTarget.innerHTML = image;
}

Problem with "document.write()" an Image Array in JavaScript

Am trying to write using document.write() an image at the time from my array. However it does not display any...
// *** Temporal variables
var i = 0;
var j = 0;
var x = 0;
// Create basic linear array
var ImgArray = []
// Do the 2D array for each or the linear array slots
for (i=0; i < 4 ; i++) {
ImgArray[i] = []
}
// Load the images
x = 0;
for(i=0; i < 4 ; i++) {
for(j=0; j < 4 ; j++) {
ImgArray[i][j] = new Image();
ImgArray[i][j] = "Images/" + x + ".jpg";
document.write("<img id= " + x + " img src=ImgArray[i][j] width='120' height='120'/>");
x = x + 1;
}
document.write("<br>");
}
What am I doing wrong?
Looks like your JavaScript isn't quite right...
document.write('<img id="' + x + '" src="' + ImgArray[i][j] + '" width="120" height="120"/>');
It looks like you're trying to do image preloading by using new Image(), but then you immediately write out an image element with the same src using document.write(), so the image will not have preloaded and you get no benefit. I also suspect you're missing a .src on one line in the inner loop:
ImgArray[i][j].src = "Images/" + x + ".jpg";
This looping to create image elements would be best done server-side when generating the HTML, but assuming that's not an option, you could lose the ImgArray variable completely:
x = 0;
for(i=0; i < 4; i++) {
for(j=0; j < 4; j++) {
document.write("<img id='" + x + "' src='Images/" + x + ".jpg' width='120' height='120'>");
x = x + 1;
}
document.write("<br>");
}
document.write writes any input the the location of script element. Try this instead:
in body
<div id="imageContainer"></div>
in your script, gather all output to a variable, say contentVariable, and then
document.getElementById("imageContainer").innerHTML = contentVariable;
note:
It's bad practice to use document.write and even innertml for appending elements to dom. use document.createElement and element.appendChild for dom manupilation.

Categories