Search code examples
javascriptcsstransform

Scaling Text to fit size of Browser with transition


I have some text that I want to size to 100% of the browser on hovering a button. How do I make this text fit the browser/container?

I know that with font size, you can do something like font-size:100vw, however the animation for font-size is jittery, so I can't use this method.

http://jsfiddle.net/0n15mfyL/

For those wondering about the jitterness, it's noticeable when the font is shrinking back down: http://jsfiddle.net/rbk48upd/


Solution

  • I'm thinking about requestAnimationFrame()

    const 
      hoverMe        = document.querySelector('#hover-me')
    , animTextSizing = document.querySelector('#anim-text-sizing')
    , txtSizeStart   = parseInt(window.getComputedStyle(animTextSizing).getPropertyValue('font-size'))
      ;
    let sizeLimit = 0,  currentTxtSize = txtSizeStart
      ;
    hoverMe.onmouseover =_=>
      {
      sizeLimit = document.body.clientWidth;
      animGrow();
      }
    hoverMe.onmouseout =_=>
      {
      sizeLimit = txtSizeStart;
      currentTxtSize++
      animReduce();
      }
    function animGrow()
      {
      animTextSizing.style['font-size'] = `${++currentTxtSize}px`;
    
      if ( animTextSizing.clientWidth < sizeLimit)
        requestAnimationFrame(animGrow);
      }
    function animReduce()
      {
      animTextSizing.style['font-size'] = `${--currentTxtSize}px`;
    
      if ( currentTxtSize > sizeLimit)
        requestAnimationFrame(animReduce);
      }
    * {
      margin  : 0;
      padding : 0;
    }
    #anim-text-sizing {
      font-size   : 30px;
      width       : fit-content;
      white-space : nowrap;
      background  : #aabfe5;
      }
    #hover-me {
      position   : fixed;
      background : red;
      color      : white;
      top        : 50%;
      left       : 50%;
      padding    : .5rem;
      cursor  : zoom-in;
      }
      <div id="hover-me">Hover me</div>
      <div id="anim-text-sizing"> Welcome to this Page </div>