11

How can I detect if a piece of text would wrap?

So imagine I have a UI with a header that has largish text. I want the biggest text here that fits vertically in a menu bar. It displays numerical data like this:

LABEL: 9999   LABEL2: 99999

The number parts can get larger. On some screens - e.g. phones - it causes the element to overflow and wrap below the bar that it is supposed to stay in. I don't want to do overflow:hidden. I want the user to see the whole thing.

I'd like to be able to somehow calculate how big the element would be, and if it would wrap pre-emptively shrink the font, possibly move the element left to make space.

Rafael Baptista
  • 11,181
  • 5
  • 39
  • 59
  • What part do you need help with? Detecting if it wraps? Decreasing the font size? Moving an element to the left? – gilly3 May 24 '13 at 22:24
  • Many of things dependency of html and css structure so putting here only asking without provide any adittional source is like asking "how build this car" and showing us only mirror from this car... – WooCaSh May 24 '13 at 22:25

2 Answers2

11

You can detect the difference between the different width properties of the containing element's width and scroll width if you set the white-space css handling to nowrap.

Here is a jsFiddle to demonstrate, and the code:

$(document).ready(function(){
    $("#messages").append($("#aa").width() + " " + $("#aa").outerWidth() + " " + $("#aa")[0].scrollWidth);
});
#aa {
    white-space: nowrap;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="aa">lksjdlakj dla ldakjl skajd lkasjlkdas dlaskdjl aksjd laksdj laks djlkas dlkasjd lkasjdl alkdj laksdj alsklkajlksjad lkajsld kasjldkasjd lkjlsk djlkasdj llaskjdl aksdjlaksjd lkasjdlak sdl</div>
<div id="messages"></div>

Once you know that the scroll width is wider than the width, you can then resize the text or do what you need to do until it isn't.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Klors
  • 2,665
  • 2
  • 25
  • 42
  • This answer would be better with the code on this site rather than a different one. You can use [Stack Snippets](https://meta.stackoverflow.com/q/358992/215552) to make that happen (I'd do it myself, but you're the copyright owner). – Heretic Monkey Aug 28 '19 at 19:37
  • 1
    @HereticMonkey Stack Snippets didn't exist when I wrote it :) feel free to port it over if you'd like – Klors Aug 29 '19 at 10:52
-2

Nice @WooCaSh. Here is an application in CoffeeScript:

autoGrow = ->
  (scope, element, attrs) ->
    update = ->
      if element[0].scrollWidth > element.outerWidth isBreaking = true else isBreaking = false
      element.css 'height', 'auto' if isBreaking
      height = element[0].scrollHeight
      element.css 'height', height + 'px'  if height > 0
    scope.$watch attrs.ngModel, update
    attrs.$set 'ngTrim', 'false'

# Register
App.Directives.directive 'autoGrow', autoGrow
Kim Miller
  • 886
  • 8
  • 11