0

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); }) 
1
  • yes without providing DOM structure how can it display..see my answer too Commented Nov 12, 2010 at 17:42

5 Answers 5

2

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); }); 
Sign up to request clarification or add additional context in comments.

Comments

1

$("#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); }); 

Comments

0

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

Comments

0

you need to provide html to that.right

<img src="" /> 

Otherwise how can it display

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.