jQuery while loop stopping prematurely

I’m working on my first WordPress plugin, a simple linked periodic table shortcode. In it I’ve set up a jQuery script that shrinks the font size within the table to fit within its parent. However, the loop stops short, leaving part of the table sitting in the parent’s padding. Can someone tell me what I’m doing wrong here?

My javascript:

Read More
jQuery(".periodic-table").each(function(index, element) {
    var textSize = 100;
    while (jQuery(element).width() > jQuery(element).parent().width()) {
        textSize -= 1;
        jQuery(element).css('font-size', textSize);
    }
});

And the full project:
https://github.com/Renkin42/WP_Plugin_PeriodicTable

Edit: I’ve put up a jsfiddle version, but for some reason it isn’t behaving the same way at all. This one seems more reliable, but tends to overshoot for some bizarre reason, making it smaller than it should be rather than bigger. Anyway, here you go: https://jsfiddle.net/rsvjwy2b/1/

Related posts

2 comments

  1. Your problem stems from your false assumption that just because the contents of a child extend beyond the bounds of its parent, the child’s width is greater than the parent’s.

    Without seeing your HTML, I’m guessing it’s something like this:

    <div class="wrap">
        <div class="periodic-table">Hello There! Hello There!</div>
    </div>
    

    When you execute your code, it compares the width of the two elements and finds that the child already is the same size or smaller than the parent and exits without doing anything. The text is sticking out, but that just means the content is overflowing .periodic-table, not .wrap.

    You can fix this by giving .periodic-table display property inline (or inline-block)

    .periodic-table {
        display: inline;
    }
    

    Inline elements’ widths are based on content – overflow isn’t part of the equation. Your current works fine with just this.

    Fiddle

  2. All right, problem solved. Some sort of bizarre loading order issue. Fixed it with jQuery(window).load() rather than just blindly running when enqued. Sorry for the trouble.

Comments are closed.