When is the appropriate time to absolutely position an element?
Specific Problem
Background
My webpage, simplified a little, looks like this:
- Title
- Large image
- Text box
I'm trying to use jquery to position a div directly above the text box. My code looks something like this (using the position API: http://docs.jquery.com/UI/Position):
div.position({
my: "left bottom",
at: "left top",
of: textbox,
});
where div has position: absolute
so as not to interfere with the flow of the page.
Problem
My problem is that even when I do this positioning on document.ready
, the div appears in the middle of the image, as though it were positioned relative to the textbox before the image was rendered.
In fact, if I print out the textbox.offset()
during the document.ready()
function and again by typing $('#textbox').offset()
, I get two different results: the first seems to be the offset of the textbox before the image is loaded while the second is the proper offset.
General Question
So my question is, is there an event I can subscribe to to know when the offset data for the textbox (generally, all elements on the page) will be correct? Or am I missing something really basic? I feel like I'm doing something wrong since this is the second 开发者_运维问答time I've encountered this problem with images. I'd prefer to stay away from "unclean" solutions like waiting after document.ready
for some fixed amount of time or interacting with the image itself.
Thanks!
I believe Jacob's answer would make it work. But some explaining would help.
onready
fires when the DOM can be manipulated. It fires before all the images and css have been loaded. In your case, you need the image to be loaded so that the browser can properly detect its width and height.
onload
fires after all the images load. That's why your offset would be correct after that event. If you don't want to wait for all the images to load, you could call your positioning code in that image's load event.
I would suggest trying to set the image's width and height inline <img src='' width='' height=''>
, so the browser doesn't have to wait to download the image though. Then you could just call it in response to the ready
event.
$(document).ready()
is designed to be a convenient alternative to using window.onload
, since in most cases all you need is for the DOM to be set up before your functions fire (so there's no need to wait for stuff like image loading, etc). However, there are cases, and I think yours is one, where window.onload
is, in fact, what you want.
精彩评论