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');
}
});
});
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With