2
votes

I have been creating an audio player using vanilla JavaScript to manipulate the HTML <audio> element.

The player is of dynamic size, with all elements scaled to fit the parent DIV.

I have applied all methods I can find for scaling font to fit the parent container and combined solutions in a way that seems functional, however I cannot make font-awesome icons scale in the same way.

The icons are contained in the following way:

HTML:

<div>
  <button>
    <a>
      <i class="fa fa-play">
      </i>
    </a>
  </button>
</div>

My solution works by implementing window.addEventListener('resize', resizeFont);, with the resizeFont function defined as follows:

JavaScript:

function resizeFont() {
  var elements  = document.getElementsByClassName('resize');
  console.log(elements);
  if (elements.length < 0) {
    return;
  }
  _len = elements.length;
  for (_i = 0; _i < _len; _i++) {
    var el = elements[_i];
    el.style.fontSize = "100%";
    for (var size = 100; el.scrollHeight > el.clientHeight; size -= 10) {
      el.style.fontSize = size + '%';
    }
  }
}

I set font-size of the div,button or a element in CSS in order to provide some input for font-awesome's default font-size: inherit style.

The resizeFont(); function is called once on page load, ensuring that the fonts displayed are scaled to fit the audio player's initial size.

I have attempted to apply the .resize class to various elements with the following results:

div: font won't display, or font displays at default size and then disappears on window resize.

a: same result as div.

i: resizeFont() on window load does scale the icon to the correct size to fit the container, but the font still disappears when the window resize event is fired.

So, I guess that the .resize class is supposed to be applied to the i element, but that I somehow need to define its size, or its container's size, differently.

1
In case anyone wishes to adapt the font-scaling method: I have set all of the plain fonts to be uncomfortably large when displayed across the body, so that they always scale down on page load (partly to test, and partly to guarantee override of default sizes). Since the elements in my audioplayer are generated dynamically, the html will not be generated unless javascript is enabled, so they can't break the rest of the page.Joshua Flood

1 Answers

-1
votes

Add the class .jcfResize to any elements containing font which should be resized.

Add the following javascript code to the page/site:

function jcfResizeText() {
    var elements  = document.getElementsByClassName('jcfResize');
    if (elements.length < 0) {
        return;
    }
    _len = elements.length;
    for (_i = 0; _i < _len; _i++) {
        var el = elements[_i];
        el.style.fontSize = "100%";
        for (var size = 100; el.scrollHeight > el.clientHeight; size -= 10) {
            el.style.fontSize = size + '%';
        }
    }
}

jcfResizeText();
window.addEventListener('resize', jcfResizeText);