Pripyat
Pripyat

Reputation: 2937

jQuery - Getting center of link

I'm trying to build a popover control for a website I'm working on, but I can't get the positioning right. I've tried various ways of getting the hyperlink's center, but it's always a little off.

I don't want to hardcode the coordinates because I need this to be universal, it needs to work with any link that I may use the popover on in the future.

What am I doing wrong here?

Here's my current method:

$('#whatsthis').click(function(e) 
{
    var _linkLocation = $(this).offset();
    $('#helpTip').css('position','absolute');

    $('#helpTip').css('left', _linkLocation.left - $(this).width()/2);

    $('#helpTip').fadeIn();
    return false;
}); 

..and here's the current output:

enter image description here

Upvotes: 2

Views: 50

Answers (2)

xdazz
xdazz

Reputation: 160883

Try the below:

$('#whatsthis').click(function(e)  {
    var _linkLocation = $(this).offset(), $helpTip = $('#helpTip');
    $helpTip.offset({ 
        'left': _linkLocation.left + $(this).width()/2 - $helpTip.width()/2,
        'top': _linkLocation.top + $(this).height()
    }).fadeIn();
    return false;
}); 

Upvotes: 1

alex
alex

Reputation: 490413

Use parenthesis to ensure you get the delta before you half it.

(_linkLocation.left - $(this).width()) / 2

Otherwise, operator precedence will bind the / 2 to the result of the width first and give you incorrect results.

Upvotes: 3

Related Questions