Brandon Cuff
Brandon Cuff

Reputation: 1478

Is there a way to detect overflow using JavaScript in html?

I'm currently attempting to make a div with text content on a web page with a "see more" button that will allow the box to expand and un-hide the overflow content. However I only want the "see more" to be visible if there is actually overflow.

Is there some way, in JavaScript, or otherwise that I can detect this?

See: http://jsfiddle.net/AJ277/

Upvotes: 0

Views: 1234

Answers (2)

bjb568
bjb568

Reputation: 11498

if (element.scrollHeight > element.offsetHeight) {
    alert('Overflow!');
}

Fiddle

Upvotes: 3

VVV
VVV

Reputation: 7603

You could simply add a wrapper around the text and compare the wrapper height to the parent height.

FIDDLE

JS

if ($('.wrapper').height() > $('#text').height()) {
    //do stuff
}
else { 
    //do other stuff like hide buttons 
}

HTML

<div id="text">
    <div class="wrapper">Lorem ipsum dolor sit amet, consectetur adipiscing elit. In in rutrum lorem. Donec eget turpis arcu. Fusce at neque libero. Nam sed risus velit. Fusce eleifend leo ac laoreet dapibus. Morbi vel tincidunt tortor. Vivamus placerat elit nec mi pulvinar, vitae volutpat nisi tempus.</div>
</div>
<button id="show">show more (only show this button if there is overflow)</button>
<button id="hide" style="display: none">hide</button>

Upvotes: 2

Related Questions