-1

I use jqueryui.com/resizable and my Question is, if it is possible that the minimum width of the <div id="yellow" class=" resizable">can be set that innerHTML text will still be fit into the element.

Here is an example of my JSFiddle: https://jsfiddle.net/awse5gmf/

HTML:

<div id="yellow" class=" resizable">

        WILL_NOT_LINE_BREAK will line break

</div>

CSS:

#yellow {
            width: 400px;
            height: 50px;
            background: yellow;                 
        }

As seen in this picture , I can resize the <div>smaller than the length of the text WILL_NOT_LINE_BREAK. I want that the minimum width of the <div> is the width of that the <div> can still contain the whole text, that means the min width should be the width of the longest word that cannot line break.

McRingRing
  • 13
  • 4

1 Answers1

0

Had to research a bit in SO, but here you go:

// http://stackoverflow.com/a/17386788/3499595
function longestWord(string) {
    var str = string.split(" ");
    var longest = 0;
    var word = null;
    for (var i = 0; i < str.length; i++) {
        if (longest < str[i].length) {
            longest = str[i].length;
            word = str[i];
        }
    }
    return word;
}


// http://stackoverflow.com/a/15302051/3499595
 $.fn.textWidth = function(text, font) {
    if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
    $.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
    return $.fn.textWidth.fakeEl.width();
};

 $(function () {
  var allText = $(".resizable").text();
  var longestWordInText = longestWord(allText);
  var longestWordWidth = $.fn.textWidth(longestWordInText, $(".resizable").css('font'));
  
   $(".resizable").resizable({
     minWidth: longestWordWidth
   });
 });
#yellow {
            width: 400px;
            height: 50px;
            background: yellow;
            font-family: Arial;
            font-size: 26px;
}
<div id="yellow" class=" resizable">
    
        WILL_NOT_LINE_BREAK will line break
    


</div>

What the JavaScript code does:

  1. A function I found in SO for finding the longest word in a string.
  2. A jQuery plugin I found in SO for calculating a word width.
  3. Main function: here we get the div's text, then we look for the longest word in that text, after that we calculate the longest word's width. And finally we apply that width to the resizable's minWidth property.

Snippet doens't work - JSFiddle: https://jsfiddle.net/yuriy636/awse5gmf/7/

Try changing also the font styles in CSS to see how it still work.

yuriy636
  • 11,171
  • 5
  • 37
  • 42