2

I'm creating a small webapplication with JS/HTML/CSS where the user has a dropdown menu to choose from 13 different images. Option 1 is default, and when the user chooses a different option the application is refreshed and the dimensions of other objects in the application adjust to the dimensions of the new image.

In order to access the image dimensions (height and width) of the 13 different images an JS loop starts and stores the dimensions in two arrays.

var height_array = []
var width_array = []

for (i = 1; i <= 13;i = i + 1) {
    var img = new Image();
    if (i <= 9){
        img.src = "img/rehe/RE0"+i+"/001.png";
    }
    else{
        img.src = "img/rehe/RE"+i+"/001.png";
    }
    height_array.push(img.height);
    width_array.push(img.width);
}

What I dont understand, is that the loop is sucessfull only part time, at times the arrays are empty or only partially populated. Naturally, the application is then built up all wrong.. A refresh helps in this case, but it is still anoying.

I have a preversion of this very simple application here: http://wieselundco.ch/plenum2/index.html Thanks in advance!

Ratnanil
  • 1,641
  • 17
  • 43

1 Answers1

2

The image has to load before you can get the dimensions

var height_array = []
var width_array  = []

for (i = 1; i <= 13;i = i + 1) {
    (function(j) {
        var img = new Image();

        img.onload = function() {
            height_array[j] = img.height;
            width_array[j]  = img.width;
        }

        if (img.complete) img.onload();

        if (j <= 9){
            img.src = "img/rehe/RE0"+j+"/001.png";
        } else {
            img.src = "img/rehe/RE"+j+"/001.png";
        }
    })(i);
}
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • wow, how fast was that!! I implemented your script and replaced my loop with yours.. I dont understand whats going wrong.. do you? – Ratnanil Apr 29 '15 at 20:24
  • You're still not getting all the dimensions ? – adeneo Apr 29 '15 at 20:30
  • You seem to be using a plugin `selectmenu`, and it's not included, hence you're getting an error – adeneo Apr 29 '15 at 20:31
  • @ adeneo: now I'm getting none of the dimensions! See http://wieselundco.ch/plenum2/index.html "Selectmenu" is from jQuery, which is included in my script.. or am I misunderstanding you? – Ratnanil Apr 29 '15 at 20:36
  • `selectmenu` is not a part of jQuery, it's part of jQuery UI. Use a current version of jQuery, not version 1.6, and include jQuery UI after jQuery – adeneo Apr 29 '15 at 20:42
  • oh.. my bad! As you might have noticed, I'm a complete noob. Thank you so much for solving 3 mistakes 33 minutes!! – Ratnanil Apr 29 '15 at 20:53