For loop exceeds the limit when using img src - javascript

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>"
);
}
});

Related

Whats wrong with my javascript loop returning xml?

I have something wrong with my loop as it is returning all the name, link, image and content in one go instead of looping through evey event individually
var items=xml.getElementsByTagName('event').length;
//alert(items);
var name, link, image, content;
for (var i = 0; i < items; i++) {
//alert('in the loop');
name = $(xml).find('name').text();
link = $(xml).find('url').text();
image = $(xml).find('image').text();
content = $(xml).find('content').text();
$('#headername')
.append('<h3>' + name + '</h3><br /><img src="' + image + '" alt="' + name +'" width="100%"><br /><p>' + content
+ '</p><h4>Read more at: </h4><a rel="external" data-role="button" data-inline="true" data-icon="back" onclick="doOpen('' + link + '', '_blank');">' +name +'</a><br />' );
}
The problem is that $(xml).find('el') returns the first element found every time through the loop, whereas you want the nth one on the nth iteration.
Try this instead:
for (var i = 0; i < items; i++) {
name = $(xml).find('name').eq(i).text();
// ^^^^^^
// ...
}
Note also that it's not a very good idea to build HTML using +, since the data could contain HTML characters. They should be escaped with escape:
.append('<h3>' + escape(name) + /* ... */ );

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;
}

Changing the content of all <pre> tags using JavaScript

I want to know how I change all the pre tags inside a document...
I'm using this:
var preContent = document.getElementById('code').innerHTML;
but this only changes the content of 1 pre tag... the one with the ID 'code'.
If you can show me how i can change all the pre tags using JavaScript I appreciate
Here's all the code:
window.onload = function () {
var preContent = document.getElementById('code').innerHTML;
var codeLine = new Array();
var newContent = '<table width="100%" border="1" '
+ 'cellpadding="0" cellspacing="0" >';
codeLine = preContent.split('\n');
for (var i = 0; i < codeLine.length; i++) {
newContent = newContent + '<tr><td class="codeTab1" >'
+ i.toString() + '</td><td class="codeTab2">'
+ codeLine[i] + '</td></tr>';
}
newContent = newContent + '</table>';
document.getElementById('code').innerHTML = newContent;
}
PS: This is to make a look like a normal compiler with numbers before the line
PPS: Each pre tag will have a different content and I want the same script to change it (if possible).
You can use getElementsByTagName:
var preElements = document.getElementsByTagName('pre');
for(var i = 0; i < preElements.length; ++ i)
{
var element = preElements[i];
/* modify element.innerHTML here */
}
First problem in you code . No two elements in a document can have same id .
So you can change it easily with jquery . look at the code .
$('pre').html("what ever text you want to show ");
Or with javascript you can do like this :
var x = document.getElementsByTagName('pre');
for(var i = 0; i < x.length; ++ i)
{
x.innerHTML = "what ever text you want to show";
}

Categories