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