likafea likafea - 1 year ago 66
HTML Question

Adding images from array with javascript

I'm trying to add an array of strings to a div and while it seemed simple enough with innerHTML, nothing seems to work.

I have a text file with urls, and i've altered them so that they'll be in proper html format (in format )

The text file comes in the following format, just with about two hundred urls:

The js code:

$.get("file.txt", function(data) {
var array = data.split('\n');
//Remove duplicate images from array
$.each(array, function(i, el){
if($.inArray(el, cleanedArray) === -1) cleanedArray.push(el);
//Remove any empty element from array
cleanedArray = cleanedArray.filter(function(n){ return n!= ""});
//turn every element into img tags
for (i=0; i<cleanedArray.length; i++) {
cleanedArray[i] ="\n" + "<img src='" + temp + "'/>";
var slideshow = document.getElementById("slideShowImages").innerHTML;

for (var i = 0; i < cleanedArray.length; i++){
slideshow += cleanedArray[i]

but while it the img tags do get added to the slideshow div's innerHTML, it still doesn't function properly. Displaying it through console.log shows it like this, with the first being the default, hardcoded, image that displays while the other is an example of how the rest are added with the code.

<img src="assets/img/default.jpg" style="opacity: 1; position: absolute; top: 0px; left: 0px;">
<img src='http://content/imagegallery/17/_12411977.jpg'/>

I've tried changing how the innerHTML is called and tried adding the inline styles, but nothing seems to make the pictures display.
Any help would be appreciated.

Answer Source

If this is your complete code, it looks to me like you are grabbing the innerHTML of the slideshow, which returns a string, and then updating that string, but never then replacing the innerHTML of the slideshow with your new string.

Try adding this after the second for loop:

//Set the inner HTML of the slideshow
document.getElementById("slideShowImages").innerHTML = slideshow;

Alternatively you could do the same with jQuery, which it looks like you have available to you (if I read the $.get() right):

//Set the inner HTML of the slideshow

While lots of things in JavaScript are references and pointers, getting the string value from innerHTML returns the string, not a reference to the property, as far as I can tell in a quick test on my end, so you will need to manually inject your new string into the property.

Hope this helps!