Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out if an element overflows (with jQuery)?

The layout looks like this:

enter image description here

Basically all I want is to find out if the ELEMENT went outside the PAGE :)

All I know is the page width, which is fixed @ 900 px...

like image 914
Alex Avatar asked Jul 28 '11 21:07

Alex


People also ask

How do you know if an element is overflow?

Select the element to check form overflow. Check its style. overflow property, if it is 'visible' then the element is hidden. Also, check if its clientWidth is less then scrollWidth or clientHeight is less then scrollHeight then the element is overflowed.

What is element overflow?

In CSS, overflow refers to any content that is too big for an element's box. This occurs when a block element has a specified height that's too small for the content it contains. You can use the CSS overflow property to control what happens to the overflow.

What is offsetHeight in jQuery?

Definition of jQuery offsetHeight. In jQuery, we can get the height of an element by using the offsetheight property in it. It is an in-built property of jQuery we can use it directly to get the viewable height of an element.

Why is Div overflowing?

Overflow happens when there is too much content to fit in a box. CSS provides various tools to manage overflow. As you go further with CSS layout and writing CSS, you will encounter more overflow situations.


2 Answers

Calculate the element's width, then get its left, finally subtract it to the page's width and you'll get the overflow.

var pageWidth = $(".page").width();
var elementWidth = $(".element").width();
var elementLeft = $(".element").position().left;

if (pageWidth - (elementWidth + elementLeft) < 0) {
  alert("overflow!");
} else {
  alert("doesn't overflow");
}
.page {
  overflow: hidden;
  width: 200px;
  height: 200px;
  position: relative;
  background: black;
}

.element {
  width: 100px;
  height: 100px;
  position: absolute;
  background: blue;
  top: 10px;
  left: 150px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="page">
  <div class="element">
  </div>
</div>

Example here: http://jsfiddle.net/jackJoe/Q5FdG/

like image 172
jackJoe Avatar answered Sep 24 '22 05:09

jackJoe


Assuming you have some <div id="elem"></div> on your page, you could tell if it is outside of the viewport like this:

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

if (left + width > $(window).width()) {
    alert('Off page to the right');
}

if (top + height > $(window).height()) {
    alert('Off page to the bottom');
}
like image 29
FishBasketGordo Avatar answered Sep 22 '22 05:09

FishBasketGordo