0

I want to create a picture preview plugin and for this i want to create a dynamic bar under the preview image with a title and so on

The Images have no consistent width so I need to adjust the bar everytime I select a new Picture.

The preview Image source is also created dynamicly with the source path of the clicked image but another directory.

To adjust the bar i ask for the preview image's width: var width = $("#maximized_image").width(); and I call this directly after I set the source of the preview image.

But my problem is that sometimes apparently the image is loaded after the width is defined so my width is 0 and my bar is not visible. Is it possible to wait for the image is loaded or force jquery to wait for it?

Or does anyone have another solution?

EDIT: Here is what I have till now:

    var img = $(this).attr("src");
    var img_split = img.split('.');
    var img_path = img_split[0];
    var rest = img_path.substring(0, img_path.lastIndexOf("/") + 1);
    var last = img_path.substring(img_path.lastIndexOf("/") + 1, img_path.length);
    var max_image = rest + "/normal/" + last + "." + img_split[1];
    $("#image_maximizer").css("height", win_h).css("width", "100%").css("display", "block").css("background", "rgba(0, 0, 0, 0.6)");
    $("#render_img").attr("src", max_image);
    var width = $("#maximized_image").width();
    alert(width);

this sets the image but i don't get the image's width

Snickbrack
  • 747
  • 2
  • 11
  • 46

2 Answers2

1

you can load the image but render it off screen, get the width then load it where you need it (you wont be loading it twice as its already loaded/cached)

I'd suggest though that you load the image THEN load in the bar with a nice fade effect or something, I'm sure a slight 300ms etc delay wont make too much difference?

Using something like onLoad for the image will say when the image is loaded but it will still have to be rendered first

atmd
  • 7,034
  • 2
  • 28
  • 62
  • 1
    When the `onload` event is fired, the DOM will have the information about the element's size whether it has been rendered by the browser or not. – Xotic750 Dec 19 '14 at 13:31
  • True, but the question was to show the bar and image at the same time, and an event onLoad will still be after the image has loaded. I guess you could combine the two concepts (onLoad or a off screen rendered image) – atmd Dec 19 '14 at 13:33
  • A crucial issue in the question is: "But my problem is that sometimes apparently the image is loaded after the width is defined so my width is 0". This has nothing to do with rendering of the actual image, even if you render off screen the image size still needs to be known first and that is known at `onload`. – Xotic750 Dec 19 '14 at 13:40
1

Run a function when the page is fully loaded including graphics:

$( window ).load(function() {
  // Run code
});

jquery load event

atmd
  • 7,034
  • 2
  • 28
  • 62
R Pelzer
  • 984
  • 12
  • 27