1

qtn: get the position of an element which is hidden using overflow:hidden property of the parent div

eg:each of he below items-1, item-2, item-3 have display-block property and some width in percent and to know the offset position/or detect the divs hidden on window resize. Display:none property is not applied to the hidden items since they are hidden by the overflow hidden property of the parent div. Please note the layout is responsive.

<div class="parent" style="width:100px; overflow:hidden;">
<ul>
<li>
 <div class="item-1">item1</div>
 <div class="item-2">item2</div>
 <div class="item-3">item3</div>
</li>
</ul>
</div>
Apurva T
  • 137
  • 1
  • 2
  • 12

2 Answers2

0

Okay, well for this question you're going to need to find out whether the element is the one visible at its location in the DOM. We're going to do this in 3 steps

  1. Find the location of the element on the dom
  2. Find the element at that location on the dom
  3. Check if that element is our original element

To find the X,Y position of the element on the DOM I just borrowed and modified this function from another stackoverflow answer (Retrieve the position (X,Y) of an HTML element):

function getOffset( el ) {
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
    }
    return { y: _y, x: _x };
}

Alright, to find the element at that location in the DOM we're going to employ

document.elementFromPoint(x,y)

Luckily, this returns the topmost element, i.e. the visible one. Finally we make sure that element is equivalent to the one we're checking. We can wrap all of this up in one, nice, big, function.

function isVisible(element){

    var getOffset = function( el ) {
            var _x = 0;
            var _y = 0;
            while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
                    _x += el.offsetLeft - el.scrollLeft;
                    _y += el.offsetTop - el.scrollTop;
                    el = el.offsetParent;
            }
            return { y: _y, x: _x };
    }
    var _pos = getOffset(element); 

    var _topElement = document.elementFromPoint(_pos.x,_pos.y);

    //Returns a boolean of whether this is this the same element?
    return _topElement == element;
}

This function will tell us whether the element is visible or not. We can just prototypically filter this through an html collection to see if the element is visible or not

[].filter.call(document.getElementsByClassName('my_thingy'),(thing) => (!isVisible(thing)));

That will return an array of all of that type of element that's not visible. Thanks for reading, I hope I helped.

Community
  • 1
  • 1
Joe Thomas
  • 5,807
  • 6
  • 25
  • 36
-2

This might give you what you need:

console.log($(".item-3").position());
Gerard
  • 15,418
  • 5
  • 30
  • 52