Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if an element is outside of its container's width?

How can I detect an element that is completely (not partially) outside of a specific containers width?

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 content div has the width of 100%, and my p tags are animated to scroll across the screen. How can I detect if they are outside of the content div so that I can remove them?

Testing for outside of the viewport is not an option since my content div also has a container.

like image 686
Fizzix Avatar asked Apr 03 '14 06:04

Fizzix


3 Answers

I believe the getBoundingClientRect() method should work well. Made a better working example using the paragraphs, here's the 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"));

Or using jQuery with the same concept:

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"));

Updated my answer because I reread that you're checking if the child is completely outside of the parent, not partially.

like image 143
Cameron Askew Avatar answered Nov 08 '22 17:11

Cameron Askew


If I understand what you're asking correctly, you could try something 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...");
}
like image 27
Andrew Newby Avatar answered Nov 08 '22 16:11

Andrew Newby


I don't know what you're trying to do, but I tried to create something similar. It's a really simple idea as far as the logic. jsfiddle here

Basically the idea was to use the width of #content div and slide the p elements over until it reached that number and then remove them.

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);
like image 1
Yes Barry Avatar answered Nov 08 '22 16:11

Yes Barry