-1

I think my code is creating an infinite loop.

  1. The page never finishes loading.
  2. It "locks up" and Chrome is forced to kill the offending page.
  3. The console doesn't refresh, so I can't read the errors.

The problem I'm trying to solve is having some text elements that are sometimes too wide, but resizing ALL of the text would make some of them really small.

My solution was to go to each header ('.mftitle h1') and compare it to it's container ('.ut-one-third') that is always an acceptable width. If the header is wider than the container, then it reduces the font-size until it isn't.

jQuery( document ).ready(function() {

  jQuery('.mftitle h1').each(function() {

    var container = jQuery(this).closest('.ut-one-third');

    while( jQuery(this).width() > jQuery(container).width() ) {

      jQuery(this).css('font-size', (parseInt(jQuery(this).css('font-size')) - 1) + "px" );

    }

  });

});

Thank you for any help! I'm stumped. And apologies if this is an awful solution, I'm teaching myself jQuery.

3 Answers3

5

Since h1 is a block element, no matter the font-size, it will take the width of the container except if specified. This mean the while loop will never be false if it iterate atleast once.

If you want the h1 to take the content width, you need to set it in display inline-block, float it or get it out of the box by absolute positioning it.

Here an example : http://jsfiddle.net/fWtwL/

Some code has been modified.

Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
0

The while loop can/will be an infinite loop if changing the font size does not make the width of the h1 less than the width of the container. Try while (jQuery(this).width() > jQuery(container).width() && parseInt(jQuery(this).css('font-size')) > 8) or something along those lines...

Hamza Kubba
  • 2,259
  • 14
  • 12
-1

The problem is actually that you are adjusting the font-size on a repetitive loop until it fits. Javascript can't pull font-size values from the stylesheet directly so its spending a lot of time trying to parse the stylesheet each time the while loop runs.

aecend
  • 2,432
  • 14
  • 16