Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect whether an element has position:fixed (possibly by parent element) via jQuery

Update I'd like to avoid walking back through all the element's parents, testing each in turn, but that is the best solution I've managed to find so far, as in this answer.


Inside an event handler, I would like to detect whether the target element's position is relative to the viewport (fixed) or the document (static, relative or absolute).

Given that an element's position might be fixed because it has "position:fixed", or because one of its parents is "position:fixed", what is an efficient way of detecting fixed positioning for the element?

For example:

CSS

#one {position:relative; height:10px; width:10px}

#two-wrapper {position:fixed; bottom:0; height:10px; width:10px}
#two {height:10px; width:10px}

HTML

<div id="one" class="trigger-event">element one</div>

<div id="two-wrapper">
    <div id="two" class="trigger-event">element two</div>
</div>

JS

$(document).ready(function(){
    $('.trigger-event').on('mouseenter', function(event){
        var isFixed = .... ????

        if (isFixed) {
            $(event.target).css('background','red'); 
        } else {
            $(event.target).css('background','green'); 
        }
    });
});
like image 964
pppggg Avatar asked Oct 20 '13 05:10

pppggg


1 Answers

Here is what I am now using to detect elements that may be nested inside a position:fixed parent. (Based on another answer which had issues with null values.)

// Returns true if `node` uses css position:fixed or has a parent that does so.
function isFixedPosition(node) {
    while (node && node.nodeName.toLowerCase() !== 'body') {
        if (window.getComputedStyle(node).getPropertyValue('position').toLowerCase() === 'fixed')
            { return true; }
        node = node.parentNode;
    }
    return false; // if got this far
}
like image 131
Robin Stewart Avatar answered Sep 28 '22 07:09

Robin Stewart