Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery offset().top is browser incompatible?

Tags:

jquery

I am trying to position an element right under some other element, but I've ran in an issue where offset() returns different values for IE and other browsers, when the page is scrolled down.

IE returns position relative to the top of the visible area (i.e. declining when you scroll down), and Firefox and Chrome always return the same value, regardless of the scrolling (which I presume is a much better behavior).

Just to clarify: what bothers me is that if none of the elements parents are relatively positioned, then offset() and position() return different values for IE, depending on how far you've scrolled down, but this is never mentioned in jQuery docs. Why is that so? Is there any way around it, that doesn't require any change of the html structure (for instance, I want to reuse one datepicker for many fields, just repositioning it slightly).

Has anyone run into the same issue?

like image 259
Egor Pavlikhin Avatar asked Sep 22 '10 01:09

Egor Pavlikhin


1 Answers

Check out this my fiddle, test by dragging red div all around.

HTML

<div id="hook"></div>
<div id="hanger"></div>

CSS

#hook {
    width: 200px;
    height: 50px;
    background-color:red;
    position: absolute;
    cursor: move;
}
#hanger {
    width: 200px;
    height: 50px;
    background-color:purple;
    position: absolute;
}

Javascript

$('document').ready(function(){
    var top = $('#hook').offset().top + $('#hook').height()+20;
    var left = $('#hook').offset().left;

    $('#hanger').css('top', top);
    $('#hanger').css('left', left);

    $('#hook').draggable({
        start: function(){
            $('#hanger').toggle();
        },
        stop: function(){
                var top = $('#hook').offset().top + $('#hook').height()+20;
                var left = $('#hook').offset().left;

                $('#hanger').css('top', top);
                $('#hanger').css('left', left);

                $('#hanger').toggle();
        }
        });
});
like image 113
Crazy Versatile Avatar answered Nov 09 '22 15:11

Crazy Versatile