How to determine if an element is outside its container width?

How can I detect an element that is completely (not partially) outside the specified width of the container?

For example, I have the following:

<div id="content">
   <div class="wrapper">
      <p>This is a paragraph</p>
      <p>This is a paragraph</p>
      <p>This is a paragraph</p>
      <p>This is a paragraph</p>
   </div>
</div>

My contentdiv is 100% wide and the tags are panimated to scroll around the screen. How can I determine if they are outside the div contentso that I can delete them?

Testing outside the viewport is not an option, since my contentdiv also has a container.

+4
source share
3 answers

I believe the method getBoundingClientRect()should work well. Made a better working example using paragraphs, here is fiddle .

function HorizontallyBound(parentDiv, childDiv) {
    var parentRect = parentDiv.getBoundingClientRect();
    var childRect = childDiv.getBoundingClientRect();

    return parentRect.left >= childRect.right || parentRect.right <= childRect.left;
}

var bound = HorizontallyBound(document.getElementById("parent"), document.getElementById("some_paragraph"));

jQuery :

function HorizontallyBound($parentDiv, $childDiv) {
    var parentRect = $parentDiv[0].getBoundingClientRect();
    var childRect = $childDiv[0].getBoundingClientRect();

    return parentRect.left >= childRect.right || parentRect.right <= childRect.left;
}

var bound = HorizontallyBound($("#parent"), $("#some_paragraph"));

, , , , .

+2

, , . . jsfiddle

, #content div p , , .

var width = $('.wrapper p:first').width(),
    i     = 0, 
    $me   = $('.wrapper p');

// slide paragraphs over to the left, once out of bounds they are removed
var interval = setInterval(function() {
    if (i == -width) {
        clearInterval(interval);
        $me.remove();
    }
    $me.css('margin-left', --i);
}, 10);
+1

If I understand correctly what you are asking, you can try something that I use on one of my own sites:

var $elem = $('#preview_link_box'),
    top = $elem.offset().top,
    left = $elem.offset().left,
    width = $elem.width(),
    height = $elem.height();


if (left + width > $(window).width()) {
    console.log("Looks like its outside the viewport...");
}
+1
source

Source: https://habr.com/ru/post/1534759/


All Articles