Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Offset().left doesn't work properly

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.

like image 516
FilipBenes Avatar asked Nov 19 '12 07:11

FilipBenes


Video Answer


2 Answers

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
like image 62
Michał Miszczyszyn Avatar answered Sep 28 '22 22:09

Michał Miszczyszyn


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; 
});
like image 31
iRaS Avatar answered Sep 29 '22 00:09

iRaS