Question

I want JavaScript to load a few img src's on page load. However my solution doesn't seem to work. Any help would be very appreciated.

HTML

<li><img id="option1" height="45px" width="75px" alt="" src=""></li>
<li><img id="option2" height="45px" width="75px" alt="" src=""></li>

JavaScript

function filltopfoto(){
    var settoppic = new Image;
    for (var i = 0; i <= itemlist;i++){
        settoppic.src = 'img' + i + '.jpg';
        $('option' + i).src = settoppic.src;
    }
}

FYI:
itemlist contains the amount of images that need to be filled. The script gets loaded on body load.

Was it helpful?

Solution

Here is the jsfiddle of the code below to show a real example.

images = ["image1/url", "image2/url"]              // define image source urls

$(document).ready(function(){                      // wait until the document is ready
    for(var i = 0; i < images.length; i++)         // loop over all images
        $('#option'+(i+1)).attr('src', images[i]); // set the src attribute, note the '#'
});

A couple of your mistakes:

  1. JQuery's $('#id') look-up requires the hashtag (#) for ids.
  2. Your filltopfoto() function is never called (Try doing alert('hello!') inside the function).
  3. Your $('options'+i) gives options0 and options1 -- you need options1 and options2
  4. Not sure why you create a new Image just to store a src variable. You can remove this code.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top