Simon
Simon

Reputation: 23141

Problem with image() object

Look at this script please

var src="some.jpg";
var img = new Image(); 
    img.src = src;
    img.id = "crop_image";
    $("#crop_image").load(function()
    {
     $("#crop_cont").append(img);
    })

why in my .load function i can't access to img element?

Thanks much

UPDATE:

But the following works

$('<img src="'+src+'" />').load(function()
                {
                    var img = new Image(); 
                    img.src = src;
                    $("#crop_cont").append(img);
                })

Upvotes: 0

Views: 198

Answers (5)

ayc
ayc

Reputation: 104

image has it's own onload event, it's probably easiest to do something like this

var src="some.jpg";
var img = new Image();

img.id = "crop_image"; 
img.onload = $("#crop_cont").append(img); // event added
img.src = src;

edit: err, I mean the Image Object.

Upvotes: 0

Alin P.
Alin P.

Reputation: 44346

$("#crop_image") will not find your new image because you haven't added it to the DOM yet. Use $(img) instead.

A correct way to do it would be:

var src="some.jpg";
var img = new Image(); 
img.src = src;
img.id = "crop_image";
$(img).load(function(){
     $("#crop_cont").append(this);
});

Upvotes: 1

kobe
kobe

Reputation: 15835

you need to provide html to that.right

<img src="" />

Otherwise how can it display

Upvotes: 0

Pointy
Pointy

Reputation: 413737

Neither of those two examples really make any sense.

In the first, you create an Image but you don't add it to the DOM. Thus, when you ask jQuery to go find it, it can't because it's not there yet.

In the second, you create a new image tag, which (internally) is going to give jQuery an actual DOM element to work with. However, that call to append your Image object to the DOM seems superfluous. You've already got an <img> so there's no need for another one.

I'd change the second one as follows:

    $('<img src="'+src+'" />').load(function()  {
      $("#crop_cont").append(this);
    });

Upvotes: 2

meder omuraliev
meder omuraliev

Reputation: 186562

#crop_image, does it actually get appended to the doc? if so when?

Upvotes: 0

Related Questions