2

I have two JavaScript functions that I want to call from inside of a jQuery function. Because I load images dynamically, I want to check the width of each image by calling the two functions func1() and func2() that will check the width.

If width < 20px then double width

I don't want to wait for the images to fully load then do the check.

I tried this but didn't work

$(document).ready(function ()
{
    $('img').each(function()
    {
       ....
    })

    func1();
    func2();
})

function func1()
{
   ....
}

function func2()
{
   ....
}

What am I missing?

RightSaidFred
  • 11,209
  • 35
  • 35
Jonas
  • 1,019
  • 4
  • 20
  • 33

3 Answers3

1

Unless the img tags have the width specified you will not be able to correctly get the width before it is completely loaded. The browser has no way of knowing what are the dimensions until it has the entire image.

Here is a way to wait until the images are loaded:

Official way to ask jQuery wait for all images to load before executing something

Community
  • 1
  • 1
epignosisx
  • 6,152
  • 2
  • 30
  • 31
0

I had a problem similar your issue. I think you have to move your functions into jquery block.

$(document).ready(function() {
    function1 () {
       ...       
    }
    function2 () {
       ... 
    }
});

Otherwise, I don't think they can be called from inside of jQuery. Test it and inform me about the result.

Mohammad Saberi
  • 12,864
  • 27
  • 75
  • 127
0

You could change this:

$(document).ready(function ()

to this:

$(window).load(function ()

to ensure that all images are loaded.


Another option would be to bind load handlers to the images themselves, but there may be issues if the images are cached.

$('img').load(function() {
    func1();
    func2();
});

You should note that this will call the functions once for each image, which may mean that you'll need to change how the functions work. Like have them receive the individual image as an argument.

RightSaidFred
  • 11,209
  • 35
  • 35
  • :( using that has the same effect as `window.onload = messWH;` which is not I want. Guess it's like what epignosisx said. But hey thanks – Jonas Dec 18 '11 at 15:02