Reputation: 15912
After some simplifications, the problem is I don't know how to set an image over another one when user clicks over the first one. It's more easy to see this in this fiddle.
What's the problem? I believe the problem is the "relative" div#problem element. If you remove the "position: relative" from the CSS everything works fine, BUT I need the relative here.
Also, I've noted that if I change the "pin container" to the alternative one (directly pending from HTML tag) everything works fine, BUT I need the "pin container" inside the relative DIV.
What's the real problem? I supposed that .offset()
will give me the position relative to the document as stated in the documentation and .offset(coordinates)
will do the same.
NOTE: The idea is the black box should appear in the same coordinates than the big image, but it appears misplaced.
NOTE2: I don't know if that's the problem, but I'm working on an Ubuntu Linux with Chrome and Firefox. Both browsers show the black box misplaced.
NOTE3: The goal is to take the coordinates of the big image and set a small box on the same position using an absolute
positioning. No tricks like setting the same margin
as the big image to the black box, sorry.
Upvotes: 1
Views: 716
Reputation: 86506
.offset()
returns the element's position relative to the whole document. What you want is to get the position relative to the offset parent (#inner
in this case). That's what .position()
is for.
$("img").click(function () {
var offset = $(this).position(); // not offset!
var $pin = $('<img>')
.addClass('pin')
.attr('src', "http://208.86.154.173/shared/images/black_box.png")
.css({top: offset.top, left: offset.left}); //.offset() works, but shouldn't
$("#pins").append($pin);
});
Add a margin of 5px to the pin (the same margin that's on the original image), and the pin appears exactly at the top left corner of the image.
Upvotes: 1
Reputation: 195972
.offset()
find the position of an element in relation to the document. You seem to want to use .position()
to find the location inside the relative
container.
See http://jsfiddle.net/T7czp/200/
You also need to apply the margin that the original image has and also apply the new dimensions with .css()
Upvotes: 2