I have a question about jQuery offset() function. I use it on my site to display "email a friend" window after clicking on email icon.
However, the window appears sticked to the right side of browser's window, not on the position of the icon. You can see it in action on http://pec.solarismedia.net/calendarday.html
$(".emailFriend").hide(); $(".emailIcon").on("click", function(e) { $(".emailFriend").css({ "position": "absolute", "left": $(this).offset().left, "top": $(this).offset().top }).fadeIn(500); return false; });
There is a picture showing the difference between intention and reality.
It's because #container
has position: relative;
. Thus absolute settings of the email box are relative to the #container. You have to either remove the property or calculate the value of left
with something like this:
$(this).offset().left - $('#container').offset().left
just use position istead. The .position() method allows us to retrieve the current position of an element relative to the offset parent. Contrast this with .offset(), which retrieves the current position relative to the document.
$(".emailFriend").insertBefore('.emailIcon').hide();
$(".emailIcon").on("click", function(e) {
$(".emailFriend").css({
"position": "absolute",
"left": $(this).position().left,
"top": $(this).position().top
}).fadeIn(500);
return false;
});
added appendTo('.userTools'). an element showing at the same position than another should be within the same element. Then position works and will work even if you change the layout.
If you don't want to change the dom structure for any reason you should use something like this:
$(".emailFriend").hide();
$(".emailIcon").on("click", function(e) {
$(".emailFriend").css({
"position": "absolute",
"left": $(this).offset().left-$(".emailFriend").offsetParent().offset().left,
"top": $(this).offset().top-$(".emailFriend").offsetParent().offset().top
}).fadeIn(500);
return false;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With