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:
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/
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:
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 propertyinline
(orinline-block
)Inline elements’ widths are based on content – overflow isn’t part of the equation. Your current works fine with just this.
Fiddle
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.