0

I'm doing a function that takes all elements with class="maximize_size" and maximize its content (text) as large as possible inside each element.

I would be happy if I could do this with a css trick, but I didn't found how.

So, I'm trying to do it with javascript/jquery... and I stucked in a point:

$(".maximize_size").each(function(){
    var element = $(this);
    var content = element.contents();

    var raiseContent = $("<div></div>");
    content.wrap(raiseContent);

    var currentSize = 10;
    while (currentSize < 150) {
        raiseContent.css({"font-size": currentSize + "px"});
        console.log(raiseContent.height() + " : " + element.height());
        if (raiseContent.height() > element.height())
            break;
        currentSize++;
    }

    element.css({"font-size": currentSize + "px"});
    content.unwrap();
});

When I use console.log(raiseContent.height()) it shows always 0 !!!

FIDDLE here.

And for that reason my break-condition inside the while never occurs.

I would be happy if you could give me some direction.

Thanks for your time.

3 Answers3

2

You don't need to add an additional element. Simply compare the container's scrollHeight to its height():

$(".maximize_size").each(function(){
  var element = $(this),
      currentSize = 10;

  while (currentSize < 150) {
    element.css({"font-size": currentSize + "px"});
    if(element[0].scrollHeight > element.height()) {
      break;
    }
    currentSize++;
  }

  element.css({"font-size": currentSize +  "px"});
});

Fiddle

Rick Hitchcock
  • 35,202
  • 5
  • 48
  • 79
1

I just modified your Js function as below:

DEMO HERE

$(".maximize_size").each(function(){
    var element = $(this);
    var content=$(this).contents();
    content.wrap('<div class="wrapped"/>');
    var raiseContent=$(this).find('.wrapped');
    var currentSize = 10;
    while (currentSize < 150) {
        raiseContent.css({fontSize:currentSize});
        console.log(raiseContent.height() + " : " + element.height());
        if (raiseContent.height() > element.height())
            break;
        currentSize++;
    }
    element.css({fontSize:currentSize});
    content.unwrap();
});
Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
0

You need to alter the height of the newly created div. Since you are checking on the height and the measurement is px.

raiseContent.css({"font-size": currentSize + "px", "height": currentSize + "px"});

http://jsfiddle.net/hfvvvuab/3/

CosX
  • 1,920
  • 2
  • 15
  • 25
  • But, if I change to other font-family, give a look here : http://jsfiddle.net/hfvvvuab/4/ –  Jun 02 '15 at 13:29