Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .offset(position) not working properly

Ok, continuing my adventure with this page. Now I have this in my page (some of the things are placeholders for now):

$(document).ready(function() {
    $(":input")
        .focus(function() {
            var localOffset = 20;
            var hint = $(this).attr("name");     // this is the placeholder part
            if(hint !== undefined)
            {
                $('#form_entry_hint').html(hint);
                var pos = $(this).offset();
                // I added rounding because it didn't work - but still not working
                pos.left = Math.round(pos.left + $(this).width() + localOffset);
                pos.top = Math.round(pos.top - 3);
                // the following alert is for debugging - it shows the correct values
                alert("top: " + pos.top + "; left: " + pos.left);
                $('#form_entry_hint').offset(pos);    // this is the line that doesn't always work
                $('#form_entry_hint').show();
            }
        })
        .blur(function() {
            $('#form_entry_hint').hide();
        });
});

This works perfectly fine on the first focus. However on subsequent execution, the #form_entry_hint is being placed waaay down and to the right. Although the debugging shows the correct values (286, 418), when it's placed with .offset(pos), it ends up at (1199, 1692) - or somewhere near there with these numbers being different every time - but always way out of place.

What am I missing this time? :)

like image 376
Aleks G Avatar asked Jan 19 '23 15:01

Aleks G


1 Answers

I get more consistent results by replacing $('#form_entry_hint').offset(pos);

With :

$('#form_entry_hint').css({ top: pos.top+'px', left: pos.left+'px' });

You'll need to set #form_entry_hint to position:absolute (or relative) if you haven't already.

EDIT: Thanks Kato for the simplification.

like image 135
leifparker Avatar answered Feb 14 '23 17:02

leifparker