0

I have a div with a static size. Sometimes longer text than the div will be placed there. Is there anyway to achieve the text fitting the div width at all times through JavaScript alone? I am aware there are jQuery fixes but need a pure JS solution in this case.

Even if you have a link to a demo/tutorial that would be helpful, thanks.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Anon Omus
  • 383
  • 4
  • 12
  • 25
  • 7
    jQuery is just an optimization of JavaScript. Let me put it another way: JavaScript can do everything jQuery can do. – TylerH May 06 '14 at 18:05
  • Native JS will always be the better route to take than to use jQuery. – ndugger May 06 '14 at 18:07
  • See http://stackoverflow.com/questions/17001302/dynamically-resize-font-size-to-fit-container-size – JJJ May 06 '14 at 18:09
  • 5
    @NickDugger I couldn't disagree with you more. If you like re-inventing the wheel, have at it. While there are plenty of cases where folks overuse and abuse jQuery, saying that it is always better to never use it is naive. – Brad May 06 '14 at 18:09
  • You're definitely free to. – ndugger May 06 '14 at 18:10
  • Especially when you need to support a bit older browsers, I'd rather use one line of jQuery than write 50 lines of vanilla JS to ensure browser compatibility. – JJJ May 06 '14 at 18:12
  • Well that all depends on how far back you need to support. It's 2014. I'd kill myself if I had to support older than IE8. – ndugger May 06 '14 at 18:13
  • @NickDugger On mobile, I do not use jQuery. On desktop, where I have to support Internet Explorer (even if only 8 and later), I use jQuery, because it really does save you a lot of time. For performance sensitive code (or for vanilla code that already works across browsers), I do not use jQuery (or use it much less). I also do not like jQuery, but it does save you wasted efforts. – PhistucK May 06 '14 at 18:16
  • http://stackoverflow.com/questions/4165836/javascript-scale-text-to-fit-in-fixed-div – Vishnuraj V May 06 '14 at 18:27

1 Answers1

0

Here you go, this should do what you want: JSFiddle

Basically the key here is to check the output.scrollHeight against output.height. Consider the following setup:

HTML:

<button onclick="addText(); resizeFont()">Click Me to Add Some Text!</button>
<div id="output"></div>

CSS:

div {
    width: 160px;
    height: 160px;
}

This creates a square div and fills it with a randomly long string of text via the addText() method.

function addText() {
    var text   = "Lorem ipsum dolor amit",
        len    = Math.floor(Math.random() * 15),
        output = document.querySelector('#output'),
        str    = [];
    for (; --len;)
        str.push(text);

    output.innerHTML = str.join(', ');
}

The magic lies in the resizeFont() function. Basically what this does is, once the text has been added, it sets the fontSize of the div to be equal to its own height. This is the base case for when you have a string of 1 character (i.e. the fontSize will equal the height). As the length of your string grows, the fontSize will need to be made smaller until the scrollHeight equals the height of the div

function resizeFont() {
    var output   = document.querySelector('#output'),
        numRE    = /(\d+)px/,
        height   = numRE.exec(window.getComputedStyle(output).height)[1],
        fontSize = height;

    // allow div to be empty without entering infinite loop
    if (!output.innerHTML.length) return;

    // set the initial font size to the height of the div
    output.style.fontSize = fontSize + 'px';

    // decrease the font size until the scrollHeight == height
    while (output.scrollHeight > height)
      output.style.fontSize = --fontSize + 'px';
}

The nice thing about this method is that you can easily attach an event listener to the resize event of the window, making the text dynamically resize as the user changes the window size: http://jsfiddle.net/QvDy8/2/

window.onload = function() {
  window.addEventListener('resize', resizeFont, false);
}
wvandaal
  • 4,265
  • 2
  • 16
  • 27
  • I found that this does not work if the height is calculated from its parent. The computed value returns "auto" in this case. I've been using `output . clientHeight` instead. – Abigail Feb 10 '22 at 01:41