0

I'm using the javascript from this older script: JavaScript: how to load all images in a folder?

However, I want to use the same javascript file to write some html code before the loop and some after the loop, all using this same javascript file.

Just putting a document.write before and after it in the javascript doesn't work.

var bCheckEnabled = true;
var bFinishCheck = false;

var img;
var imgArray = new Array();
var i = 0;

var myInterval = setInterval(loadImage, 1);

function loadImage() {

    if (bFinishCheck) {
        clearInterval(myInterval);
        document.write('Loaded ' + i + ' image(s)');
        return;
    }

    if (bCheckEnabled) {

        bCheckEnabled = false;

        img = new Image();
        img.onload = fExists;
        img.onerror = fDoesntExist;
        img.src = 'assets/' + i + '.png';
        document.write('<img src="assets/' + i + '.png" width="1016" height="813" alt="Kar" />');

    }

}

function fExists() {
    imgArray.push(img);
    i++;
    bCheckEnabled = true;
}

function fDoesntExist() {
    bFinishCheck = true;
}
Community
  • 1
  • 1
Nick Groeneveld
  • 895
  • 6
  • 18

1 Answers1

-1

You may be using this example code incorrectly. Its intent appears to be to pre-load the image files in the background, not display them to the user in the HTML (yet). This is to improve apparent download speed of your page.

In short, this code doesn't actually render the image into the DOM; and that is intentional behavior.

Jim Ankrom
  • 66
  • 1
  • 2
  • Alright, thank you. Can you help me with my initial goal then? Loop through a number of files and place them between tags? – Nick Groeneveld Jun 05 '14 at 14:54
  • What you're looking for is called DOM Manipulation. My first inclination would be to point you to the [jQuery](http://www.jquery.com) library. Otherwise, I could solve your problem with direct DOM manipulation ( see (https://developer.mozilla.org/en-US/docs/Web/API/document.createElement) for a basic start ) but I think you're best suited using jQuery to do so. – Jim Ankrom Jun 05 '14 at 15:02
  • Hmm, alright. Can you give me a start with the jquery? – Nick Groeneveld Jun 05 '14 at 15:35
  • This *should* give you a number of good starts: http://stackoverflow.com/questions/10863658/load-image-with-jquery-and-append-it-to-the-dom If that doesn't answer your question, I'd need you to clarify a bit what exactly you're looking to do. You seem to be asking to "add html to the loop" but all I see in your example code is adding width/height/alt attributes to the image itself. This could/should be done through the attributes on the image object, which would appear in the html once added to the DOM (appended to an element in your document). – Jim Ankrom Jun 05 '14 at 18:19