jQuery Offset().left doesn't work properly

FilipBenes picture FilipBenes · Nov 19, 2012 · Viewed 31.7k times · Source

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.

Answer

Michał Miszczyszyn picture Michał Miszczyszyn · Nov 19, 2012

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