Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to determine if an element is wrapped?

Basically, I have a certain HTML element (in this case, a div) that is wrapping to a new line in the case of a below average screen resolution, due to a floating element. I want to control this behavior, placing and/or styling the element differently if indeed it is currently wrapped or will be wrapped upon resize/onload.

Is this possible?

like image 810
Chris Cashwell Avatar asked Feb 01 '11 13:02

Chris Cashwell


People also ask

How do you prevent elements from wrapping?

If you want to prevent the text from wrapping, you can apply white-space: nowrap; Notice in HTML code example at the top of this article, there are actually two line breaks, one before the line of text and one after, which allow the text to be on its own line (in the code).


1 Answers

You can count the number of text rectangles it has using element.getClientRects(), which returns a ClientRect object for each border-box of an element. This must be done on an inline element such as a <span> for each line of text to have its own border-box, but it's simple enough to use:

window.onresize = function () {
    var span = document.getElementById("myDiv").getElementsByTagName("span")[0],
        rect = span.getClientRects();

    if (rect.length > 1) // more than 1 line of text
        doSomethingWithElement(span.parentNode);
}
like image 178
Andy E Avatar answered Oct 18 '22 08:10

Andy E