NedStarkOfWinterfell
NedStarkOfWinterfell

Reputation: 5153

jQuery offsetparent returns non-positioned parent also

I am trying out the following code:

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("span").click(function(){
    alert($(this).offsetParent().length);
  });
});
</script>
</head>
<body>
<p>If you click on me, I will disappear.</p>
<p><span>Click me away!</span></p>
<p>Click me too!</p>
</body>
</html>

From the jQuery documentation, offsetParent() is supposed to return the closest positioned parent, positioned meaning one with position defined explicitly as 'static,absoluteorrelative`. here, none is declared for any element, yet the alert pops up 1. How come?

Upvotes: 1

Views: 634

Answers (1)

Minko Gechev
Minko Gechev

Reputation: 25682

First, let as look at the return result:

[html, prevObject: jQuery.fn.jQuery.init[1], context: span, jquery: "1.9.0", constructor: function, init: function…]

So for $(span).offsetParent() you get the HTML element.

Now let's look at the implementation of offsetParent:

offsetParent: function() {
    return this.map(function() {
        var offsetParent = this.offsetParent || document.documentElement;
        while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
            offsetParent = offsetParent.offsetParent;
        }
        return offsetParent || document.documentElement;
    });
}

From the code above we see that if we don't have positioned parent offsetParent returns the HTML element.

The only bad things is that when I looked at the documentation that wasn't there.

To check whether there's actually an offsetParent you can use:

document.getElementsByTagName('html')[0] === $(elem).offsetParent()[0]

Upvotes: 4

Related Questions