Javascript: Detecting if text would wrap

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.

Tags:

Javascript