jQuery script efficiency - javascript

I use the below jQuery function named textfill on hundreds of divs. Basically it resizes the inner text to fit the enclosing div such that the font-size of the text is maximum, So longer texts are smaller than shorter ones but are at maximum font size that they can be without overflowing from the div.
; (function($) {
/**
* Resizes an inner element's font so that the inner element completely fills the outer element.
* #version 0.1
* #param {Object} Options which are maxFontPixels (default=40), innerTag (default='span')
* #return All outer elements processed
* #example <div class='mybigdiv filltext'><span>My Text To Resize</span></div>
*/
$.fn.textfill = function(options) {
var defaults = {
maxFontPixels: 40,
innerTag: 'span'
};
var Opts = jQuery.extend(defaults, options);
return this.each(function() {
var fontSize = Opts.maxFontPixels;
var ourText = $(Opts.innerTag + ':visible:first', this);
var maxHeight = $(this).height();
var maxWidth = $(this).width();
var textHeight;
var textWidth;
do {
ourText.css('font-size', fontSize);
textHeight = ourText.height();
textWidth = ourText.width();
fontSize = fontSize - 1;
} while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
var pos = (maxHeight-textHeight)/2;
ourText.css('top', pos +'px');
});
};
})(jQuery);
Because I run this script on hundreds of divs that look like:
<div class="textDiv"><span>text appears here</span></div>
At the same time using:
$('.textDiv').each(function() { $(this).textfill({ maxFontPixels: 28 })});
It takes 40 to 70 seconds depending on the amount of divs. I desperately need to tune the code so it will run faster. I've tried for the last two hours but can't seem to make it run faster. Can someone help?
EDIT:
Took some input from the comments and changed the code to:
var items = document.getElementsByClassName("textDiv");
for (var i = items.length; i--;) {
$(items[i]).textfill({ maxFontPixels: 28 });
}
It seems to be a bit faster but still really slow.

$('.textDiv').each(function() { $(this).textfill({ maxFontPixels: 28 })});
You're using the function wrong. Every (proper) plugin does already work on jQuery collections, and has the each built-in so that you do not need to put it around the invocation. Just do
$('.textDiv').textfill({ maxFontPixels: 28 });
Yet I think that is not your actual problem; loops are quite fast and even for hundred items it won't take seconds. The problem is
ourText.css('font-size', fontSize);
textHeight = ourText.height();
textWidth = ourText.width();
inside a loop (actually in two nested loops), as it requires a complete reflow by the browser. You will need to minimize the calls to this part, for example by using some kind of binary search (bisection) and/or by applying a interpolation metric that approximates the font size (number of characters divided by area for example?) to get a good starting value.
Beside that, there might be other minor optimisations:
cache $(this)
$(Opts.innerTag + ':visible:first', this); looks like a quite complex selector. Is that really necessary, do you expect hidden elements? Move such extras to the options, and go with $(this).children().first() by default.
I'm not sure about your CSS, but how do you set the dimensions of your divs (which you retrieve as maxHeight/maxWidth)? For reducing the reflow costs when changing the fontsize inside, an additional overflow:hidden can help.

Obviously the bottle neck is the inner-most looping (the next is parent of inner-most and so on).
Why don't use "bisection" for finding out the font size?:
For 200 divs:
Bisect solution (needs some refactoring):
http://jsfiddle.net/nx2n2/8/
Time: ~700
Current solution:
http://jsfiddle.net/pXL5z/3/
Time: ~1400
The most important code:
var change = Math.ceil(fontSize / 2);
while(true) {
change = Math.ceil(change / 2);
var prev = fontSize;
do {
fontSize = fontSize - change;
ourText.css('font-size', fontSize);
textHeight = ourText.height();
textWidth = ourText.width();
} while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3);
change = Math.ceil(change / 2);
while (textHeight < maxHeight && textWidth < maxWidth) {
fontSize = fontSize + change;
ourText.css('font-size', fontSize);
textHeight = ourText.height();
textWidth = ourText.width();
}
var current = fontSize;
if(prev == current) {
break;
}
}
// this is because you subtract after change in your original solution
// only for 'compatibility' with original solution
fontSize = fontSize - 1;

Related

Limiting an element from appearing out of the screen

I'm trying to make a square appear at random positions of the screen. I have set it's position property to be absolute and in javascript i'm running a random number between 0 to 100, this will then be assigned as a percentage to top and left property. however if the random number was ~100 or a bit less the square will appear out of the screen. How do I fix this problem?
var shape1 = document.getElementById("shape1");
//creating random number to 100
function randomNum() {
var r = Math.random();
var y = (r * (100 - 0 + 1)) + 0;
var x = Math.floor(y);
console.log(x);
return x;
}
//reappear at random position
function reappear(object) {
object.style.left = randomNum().toString() + "%";
object.style.top = randomNum().toString() + "%";
object.style.display = "block";
}
reappear(shape1);
code: https://jsfiddle.net/y3m4ygow/1/
You can call the getBoundingClientRect method (MDN reference) on the object and check to see if its bottom property is bigger than window.innerHeight (means it's falling outside the window height), or if its right property is bigger than window.innerWidth (means it's falling outside the window width), and if so, call the reappear function again:
function reappear(object) {
object.style.left = randomNum().toString() + "%";
object.style.top = randomNum().toString() + "%";
object.style.display = "block";
var rect = object.getBoundingClientRect();
if(rect.right > window.innerWidth || rect.bottom > window.innerHeight)
reappear(object);
}
Fiddle update: https://jsfiddle.net/y3m4ygow/2/
As you can see what's happening here is sometimes the object falling out of the document because (the width or height of it + the randomized percentage) is more than document width or height.
For example, say that document width is 1000px and the random number turned out to be 90% (=900px), since the box width is 200px, so you will have 100px out of the screen.
Now you have two solutions:
First: As #Sidd noted, you can check whether the box is in or out using getBoundingClientRect this will return a variable for you having two properties one is bottom which is the distance of the box from the upper edge of the document, the other property is height which is the distance of the box from the left border of the screen.
Now what you can do is compare those two values with the document width and height.
Now by adding those three lines you'll have your problem solved:
var rect = object.getBoundingClientRect(); // getting the properties
if(rect.right > window.innerWidth // comparing width
|| rect.bottom > window.innerHeight) // comparing height
{reappear(object);} // re-randomizing
https://jsfiddle.net/y3m4ygow/2/
this WILL work, but it might produce some flickering with some browsers, and i'm not very comfortable about calling a function inside itself.
Second Solution is: which is what I would prefer you to do, is by not using a percentage, but using a fixed height and width values.
you can get the current height and weight values from the window object and substract your box dimensions from it:
var cHeight = window.innerHeight - 200;
var cWidth = window.innerWidth - 200;
set those two as the maximum value for the top and the right.
function topRandomNum() {
var r = Math.random();
var y = (r * (cHeight - 0 + 1)) + 0;
var x = Math.floor(y);
return x;
}
function rightRandomNum() {
var r = Math.random();
var y = (r * (cWidth - 0 + 1)) + 0;
var x = Math.floor(y);
return x;
}
and here's the fiddle for the second solution: https://jsfiddle.net/uL24u0e4/

Adjust position of a group of adjacent divs in non-linear fashion

This isn't so much a jQuery question as it is an overall conceptual question.
In my example I can populate a container with divs that have a top value set in a nonlinear fashion.
The top value of each one is calculated based on a formula that takes into account the top position of the one to its left as well as the height of the container (line 33 of fiddle).
//this formula sets the top value for each new child added to the container
//height is 100% of its parent which is 20% of the body
//newOne:last is the most recently added child and will have an initial top value of 10%
parseInt($(this).next().css('top'), 10) / $('#queue').height()) * 75 + (parseInt($('.newOne:last').css('top'), 10) * 2) + '%'
I more of less stumbled upon this by chance and it seems to work 'ok', but if an optimization is obvious to you, please point it out :)
What I'm having trouble coming up with is an elegant formula for how to adjust the children smoothly during a drag event. I'm thinking the top value needs to be adjusted based on some manipulation of the left offset, but after hours of experimenting, I haven't found anything that keeps the original position intact when I start dragging and continues adjusting the values smoothly during my drag. The children should gradually approach a minimum top value of 10% as I drag left (child with left offset of 0 will have a top value of 10%), and gradually move away from that top value back toward their initial position as I drag right.
$('#queue').draggable({
axis: "x",
scroll: false,
drag: function(){
//adjust values of each child
$('.newOne').each(function(){
var percentLeft = $(this).offset().left / $('footer').width() * 100
var thisLeft = parseInt($(this).css('left'), 10) / $(window).width() * 100;
var thisTop = parseInt($(this).css('top'), 10) / $('#queue').height() * 100;
if (percentLeft >= 0){
//top value of each one gradually decreases...
//as it gets closer to an offset value of 0 and minimum top value of 10%
//non-linear attempt but not even close
//$(this).css('top', $(this).css('top', 10 + (thisTop - 10 / thisLeft) + '%'));
//linear step
$(this).css({'top': 8 + (percentLeft/2) + '%'});
}
});
}
});
http://jsfiddle.net/5RRCS/17/
P.S. I know I'm asking a lot here, but hopefully someone is up to the challenge :)
Update:
Stumbled onto exp method and did something like this:
adjustTop = function(offset){
return 100 * (1.0-Math.min(0.98,(0.83 + ( 0.17/ (Math.exp(0.007*offset))) )) ) + '%';
};
$(this).css('top', adjustTop($(this).offset().left) );
Here's a version that I believe does what you are looking for.
The first thing I did was to refactor the top calculation so that both the initialization and the drag handlers would get the same results.
Rather than calculate the positions of the child divs based on their offset to the document, I changed the logic to use position relative to their container.
I also remove z-index as the child divs already being added the parent with the correct stacking order - the left most child is the last element in the container.
Calculating the height of each child depended on whether #queue's current position was to the left or right of its origin.
I also change the iteration logic to behave the same to simplify calculating the current elements starting offset:
$($('.newOne').get().reverse()).each(function (index) {
$(this).css({
'background': 'rgba(255,255,255,.80)',
'top': calcTop($(this), index)
});
});
Code for positioning the child elements:
function calcTop($ele, index) {
var elePositionLeft = $ele.position().left;
var queuePositionLeft = $('#queue').position().left;
var footerWidth = $('footer').width();
var queueHeight = $('#queue').height();
var distanceToTravel = queuePositionLeft < 0 ? elePositionLeft : footerWidth - elePositionLeft;
var percentTraveled = Math.abs(queuePositionLeft) / distanceToTravel;
var thisPercentLeft = (elePositionLeft + queuePositionLeft) / footerWidth;
var queuePercentLeft = queuePositionLeft / footerWidth;
var newTop;
var myStartOffset = (index + 1) * startOffset;
var topTravel = queuePositionLeft < 0 ? -myStartOffset + startOffset : (queueHeight - startOffset);
var linear = false;
if (linear) {
newTop = myStartOffset + (topTravel * percentTraveled);
newTop = newTop > startOffset ? Math.round(newTop) : startOffset;
return newTop;
} else {
if (queuePositionLeft >= 0) {
newTop = myStartOffset + (topTravel * thisPercentLeft * percentTraveled);
newTop = newTop > startOffset ? Math.round(newTop) : startOffset;
} else {
newTop = myStartOffset + (topTravel * (1+thisPercentLeft) * percentTraveled);
newTop = newTop < startOffset ? startOffset : Math.round(newTop);
}
return newTop;
}
}
There was also a minor bug in the reset function - it wasn't setting childCount back to zero:
$('#reset').click(function () {
$('#queue').empty().css('left', 0);
childCount = 0;
});
Demo Fiddle

Centering via offset math doesn't work in non-webkit browsers

The code: http://jsfiddle.net/LPF85/6/
In FF, IE7, and IE9 (the only browsers I've tested that don't run WebKit), it seems that the left attribute is either always set to 0, or, in IE's case, negative.
My positioning code is all based off the dimensions of the document.
function open_img_in_face_box(id, width){
max_width = $j(document).width();
max_height = $j(document).height();
padding = 150;
passed_width = width || (max_width - (2 * padding));
var img = $j('#' + id);
dom_img = document.getElementById(id);
$j(document).bind('reveal.facebox', function() {
$j("#facebox .image img").width(passed_width);
})
// display
jQuery.facebox({
image: img.attr('src')
});
// center and adjust size
var aspect_ratio = img.width() / img.height();
var img_width = passed_width;
var img_height = passed_width / aspect_ratio;
window_center_y = max_height / 2;
window_center_x = max_width / 2;
offset_y = window_center_y - (img_height / 2);
offset_x = window_center_x - (img_width / 2);
var fbx = $j('#facebox');
fbx.css('position', 'absolute');
fbx.css('left', offset_x + 'px !important');
fbx.css('top', offset_y + 'px !important');
fbx.css('margin-left', 'auto');
fbx.css('margin-right', 'auto');
}
margin-left and margin-right don't appear to do anything here, which I'm fine with, because the left math should work across all browsers, right? (It is just math)
The goal of the facebox / lightbox, is to be centered both horizontally and vertically.
Why would you even programatically calculate the position in the first place? What if the user resizes the page? This can easily be done in pure CSS.
I don't really understand your jsFiddle (or am I not seeing the same thing?) so I'll just give you this script: http://jsfiddle.net/minitech/8U4Ke/ that can be modified however you like. It's commented. ;)
Now it's easy to hide and show - to hide, fade out .overlay. To show, fade it in. To change the contents, replace the HTML in .popup. Add close boxes and whatnot liberally.

jQuery vertical bubble marquee HTML elements

I'm searching for a good vertical bubble marquee plugin.
Not simple vertical marquee, I'm looking for a good "flash like" effects plugin, something smooth with element marquee from bottom to top of a div content.
Could be really nice but I think it's only in my dreams this plugin
Well, it's not terribly efficient, but this is a good start I think:
jQuery.fn.verticalMarquee = function(vertSpeed, horiSpeed) {
this.css('float', 'left');
vertSpeed = vertSpeed || 1;
horiSpeed = 1/horiSpeed || 1;
var windowH = this.parent().height(),
thisH = this.height(),
parentW = (this.parent().width() - this.width()) / 2,
rand = Math.random() * 1000,
current = this;
this.css('margin-top', windowH + thisH);
this.parent().css('overflow', 'hidden');
setInterval(function() {
current.css({
marginTop: function(n, v) {
return parseFloat(v) - vertSpeed;
},
marginLeft: function(n, v) {
return (Math.sin(new Date().getTime() / (horiSpeed * 1000) + rand) + 1) * parentW;
}
});
}, 15);
setInterval(function() {
if (parseFloat(current.css('margin-top')) < -thisH) {
current.css('margin-top', windowH + thisH);
}
}, 250);
};
$('.message').verticalMarquee(0.5, 1);
It uses Math.sin to move the element horizontally. The function verticalMarquee accepts two arguments, one for vertical speed and the other for horizontal speed. The function can only be called on jQuery objects that contains only one element - during testing anything more than one element been animated at once caused terrible amount of lagging.
See a simple demo here: http://jsfiddle.net/CcccQ/2/
Do you mean something like The Silky Smooth Marquee plugin?

Calculate text width with JavaScript

I'd like to use JavaScript to calculate the width of a string. Is this possible without having to use a monospace typeface?
If it's not built-in, my only idea is to create a table of widths for each character, but this is pretty unreasonable especially supporting Unicode and different type sizes (and all browsers for that matter).
In HTML 5, you can just use the Canvas.measureText method (further explanation here).
Try this fiddle:
/**
* Uses canvas.measureText to compute and return the width of the given text of given font in pixels.
*
* #param {String} text The text to be rendered.
* #param {String} font The css font descriptor that text is to be rendered with (e.g. "bold 14px verdana").
*
* #see https://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
*/
function getTextWidth(text, font) {
// re-use canvas object for better performance
const canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
const context = canvas.getContext("2d");
context.font = font;
const metrics = context.measureText(text);
return metrics.width;
}
function getCssStyle(element, prop) {
return window.getComputedStyle(element, null).getPropertyValue(prop);
}
function getCanvasFont(el = document.body) {
const fontWeight = getCssStyle(el, 'font-weight') || 'normal';
const fontSize = getCssStyle(el, 'font-size') || '16px';
const fontFamily = getCssStyle(el, 'font-family') || 'Times New Roman';
return `${fontWeight} ${fontSize} ${fontFamily}`;
}
console.log(getTextWidth("hello there!", "bold 12pt arial")); // close to 86
If you want to use the font-size of some specific element myEl, you can make use of the getCanvasFont utility function:
const fontSize = getTextWidth(text, getCanvasFont(myEl));
// do something with fontSize here...
Explanation: The getCanvasFontSize function takes some element's (by default: the body's) font and converts it into a format compatible with the Context.font property. Of course any element must first be added to the DOM before usage, else it gives you bogus values.
More Notes
There are several advantages to this approach, including:
More concise and safer than the other (DOM-based) methods because it does not change global state, such as your DOM.
Further customization is possible by modifying more canvas text properties, such as textAlign and textBaseline.
NOTE: When you add the text to your DOM, remember to also take account of padding, margin and border.
NOTE 2: On some browsers, this method yields sub-pixel accuracy (result is a floating point number), on others it does not (result is only an int). You might want to run Math.floor (or Math.ceil) on the result, to avoid inconsistencies. Since the DOM-based method is never sub-pixel accurate, this method has even higher precision than the other methods here.
According to this jsperf (thanks to the contributors in comments), the Canvas method and the DOM-based method are about equally fast, if caching is added to the DOM-based method and you are not using Firefox. In Firefox, for some reason, this Canvas method is much much faster than the DOM-based method (as of September 2014).
Performance
This fiddle compares this Canvas method to a variation of Bob Monteverde's DOM-based method, so you can analyze and compare accuracy of the results.
Create a DIV styled with the following styles. In your JavaScript, set the font size and attributes that you are trying to measure, put your string in the DIV, then read the current width and height of the DIV. It will stretch to fit the contents and the size will be within a few pixels of the string rendered size.
var fontSize = 12;
var test = document.getElementById("Test");
test.style.fontSize = fontSize;
var height = (test.clientHeight + 1) + "px";
var width = (test.clientWidth + 1) + "px"
console.log(height, width);
#Test
{
position: absolute;
visibility: hidden;
height: auto;
width: auto;
white-space: nowrap; /* Thanks to Herb Caudill comment */
}
<div id="Test">
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
</div>
Here's one I whipped together without example. It looks like we are all on the same page.
String.prototype.width = function(font) {
var f = font || '12px arial',
o = $('<div></div>')
.text(this)
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
.appendTo($('body')),
w = o.width();
o.remove();
return w;
}
Using it is simple: "a string".width()
**Added white-space: nowrap so strings with width larger than the window width can be calculated.
I like your "only idea" of just doing a static character width map! It actually works well for my purposes. Sometimes, for performance reasons or because you don't have easy access to a DOM, you may just want a quick hacky standalone calculator calibrated to a single font. So here's one calibrated to Helvetica; pass a string and a font size:
const widths = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.2796875,0.2765625,0.3546875,0.5546875,0.5546875,0.8890625,0.665625,0.190625,0.3328125,0.3328125,0.3890625,0.5828125,0.2765625,0.3328125,0.2765625,0.3015625,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.5546875,0.2765625,0.2765625,0.584375,0.5828125,0.584375,0.5546875,1.0140625,0.665625,0.665625,0.721875,0.721875,0.665625,0.609375,0.7765625,0.721875,0.2765625,0.5,0.665625,0.5546875,0.8328125,0.721875,0.7765625,0.665625,0.7765625,0.721875,0.665625,0.609375,0.721875,0.665625,0.94375,0.665625,0.665625,0.609375,0.2765625,0.3546875,0.2765625,0.4765625,0.5546875,0.3328125,0.5546875,0.5546875,0.5,0.5546875,0.5546875,0.2765625,0.5546875,0.5546875,0.221875,0.240625,0.5,0.221875,0.8328125,0.5546875,0.5546875,0.5546875,0.5546875,0.3328125,0.5,0.2765625,0.5546875,0.5,0.721875,0.5,0.5,0.5,0.3546875,0.259375,0.353125,0.5890625]
const avg = 0.5279276315789471
function measureText(str, fontSize) {
return Array.from(str).reduce(
(acc, cur) => acc + (widths[cur.charCodeAt(0)] ?? avg), 0
) * fontSize
}
That giant ugly array is ASCII character widths indexed by character code. So this just supports ASCII (otherwise it assumes an average character width). Fortunately, width basically scales linearly with font size, so it works pretty well at any font size. It's noticeably lacking any awareness of kerning or ligatures or whatever.
To "calibrate" I just rendered every character up to charCode 126 (the mighty tilde) on an svg and got the bounding box and saved it to this array; more code and explanation and demo here.
This works for me...
// Handy JavaScript to measure the size taken to render the supplied text;
// you can supply additional style information too if you have it.
function measureText(pText, pFontSize, pStyle) {
var lDiv = document.createElement('div');
document.body.appendChild(lDiv);
if (pStyle != null) {
lDiv.style = pStyle;
}
lDiv.style.fontSize = "" + pFontSize + "px";
lDiv.style.position = "absolute";
lDiv.style.left = -1000;
lDiv.style.top = -1000;
lDiv.textContent = pText;
var lResult = {
width: lDiv.clientWidth,
height: lDiv.clientHeight
};
document.body.removeChild(lDiv);
lDiv = null;
return lResult;
}
jQuery:
(function($) {
$.textMetrics = function(el) {
var h = 0, w = 0;
var div = document.createElement('div');
document.body.appendChild(div);
$(div).css({
position: 'absolute',
left: -1000,
top: -1000,
display: 'none'
});
$(div).html($(el).html());
var styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'];
$(styles).each(function() {
var s = this.toString();
$(div).css(s, $(el).css(s));
});
h = $(div).outerHeight();
w = $(div).outerWidth();
$(div).remove();
var ret = {
height: h,
width: w
};
return ret;
}
})(jQuery);
The ExtJS javascript library has a great class called Ext.util.TextMetrics that "provides precise pixel measurements for blocks of text so that you can determine exactly how high and wide, in pixels, a given block of text will be". You can either use it directly or view its source to code to see how this is done.
http://docs.sencha.com/extjs/6.5.3/modern/Ext.util.TextMetrics.html
I wrote a little tool for that. Perhaps it's useful to somebody. It works without jQuery.
https://github.com/schickling/calculate-size
Usage:
var size = calculateSize("Hello world!", {
font: 'Arial',
fontSize: '12px'
});
console.log(size.width); // 65
console.log(size.height); // 14
Fiddle: http://jsfiddle.net/PEvL8/
<span id="text">Text</span>
<script>
var textWidth = document.getElementById("text").offsetWidth;
</script>
This should work as long as the <span> tag has no other styles applied to it.
offsetWidth will include the width of any borders, horizontal padding, vertical scrollbar width, etc.
You can use the canvas so you don't have to deal so much with css properties:
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
ctx.font = "20pt Arial"; // This can be set programmaticly from the element's font-style if desired
var textWidth = ctx.measureText($("#myElement").text()).width;
In case anyone else got here looking both for a way to measure the width of a string and a way to know what's the largest font size that will fit in a particular width, here is a function that builds on #Domi's solution with a binary search:
/**
* Find the largest font size (in pixels) that allows the string to fit in the given width.
*
* #param {String} text - The text to be rendered.
* #param {String} font - The css font descriptor that text is to be rendered with (e.g. "bold ?px verdana") -- note the use of ? in place of the font size.
* #param {Number} width - The width in pixels the string must fit in
* #param {Number} minFontPx - The smallest acceptable font size in pixels
* #param {Number} maxFontPx - The largest acceptable font size in pixels
**/
function GetTextSizeForWidth(text, font, width, minFontPx, maxFontPx) {
for (;;) {
var s = font.replace("?", maxFontPx);
var w = GetTextWidth(text, s);
if (w <= width) {
return maxFontPx;
}
var g = (minFontPx + maxFontPx) / 2;
if (Math.round(g) == Math.round(minFontPx) || Math.round(g) == Math.round(maxFontPx)) {
return g;
}
s = font.replace("?", g);
w = GetTextWidth(text, s);
if (w >= width) {
maxFontPx = g;
} else {
minFontPx = g;
}
}
}
You can also do this with createRange, which is more accurate, than the text cloning technique:
function getNodeTextWidth(nodeWithText) {
var textNode = $(nodeWithText).contents().filter(function () {
return this.nodeType == Node.TEXT_NODE;
})[0];
var range = document.createRange();
range.selectNode(textNode);
return range.getBoundingClientRect().width;
}
The code-snips below, "calculate" the width of the span-tag, appends "..." to it if its too long and reduces the text-length, until it fits in its parent (or until it has tried more than a thousand times)
CSS
div.places {
width : 100px;
}
div.places span {
white-space:nowrap;
overflow:hidden;
}
HTML
<div class="places">
<span>This is my house</span>
</div>
<div class="places">
<span>And my house are your house</span>
</div>
<div class="places">
<span>This placename is most certainly too wide to fit</span>
</div>
JavaScript (with jQuery)
// loops elements classed "places" and checks if their child "span" is too long to fit
$(".places").each(function (index, item) {
var obj = $(item).find("span");
if (obj.length) {
var placename = $(obj).text();
if ($(obj).width() > $(item).width() && placename.trim().length > 0) {
var limit = 0;
do {
limit++;
placename = placename.substring(0, placename.length - 1);
$(obj).text(placename + "...");
} while ($(obj).width() > $(item).width() && limit < 1000)
}
}
});
The better of is to detect whether text will fits right before you display the element. So you can use this function which doesn't requires the element to be on screen.
function textWidth(text, fontProp) {
var tag = document.createElement("div");
tag.style.position = "absolute";
tag.style.left = "-999em";
tag.style.whiteSpace = "nowrap";
tag.style.font = fontProp;
tag.innerHTML = text;
document.body.appendChild(tag);
var result = tag.clientWidth;
document.body.removeChild(tag);
return result;
}
Usage:
if ( textWidth("Text", "bold 13px Verdana") > elementWidth) {
...
}
You can use max-content to measure the pixel width of text.
Here is a utility function that does that. It optionally takes any node as a context to calculate the width in, taking into account any CSS like font-size, letter-spacing, etc.
function measureTextPxWidth(
text,
template = document.createElement("span")
) {
const measurer = template.cloneNode();
measurer.style.setProperty("all", "revert", "important");
measurer.style.setProperty("position", "position", "important");
measurer.style.setProperty("visibility", "hidden", "important");
measurer.style.setProperty("width", "max-content", "important");
measurer.innerText = text;
document.body.appendChild(measurer);
const { width } = measurer.getBoundingClientRect();
document.body.removeChild(measurer);
return width;
}
document.querySelector('.spanTextWidth').innerText =
`${measureTextPxWidth('one two three')}px`
document.querySelector('.h1TextWidth').innerText =
`${measureTextPxWidth('one two three', document.querySelector('h1'))}px`
h1 {
letter-spacing: 3px;
}
<span>one two three</span>
<div class="spanTextWidth"></div>
<h1>one two three</h1>
<div class="h1TextWidth"></div>
If you're okay with installing a package, and you want perhaps a more authoritative or precise answer, you can use opentype.js (surprised no one has mentioned this yet):
import { load } from "opentype.js";
const getWidth = async (text = "Hello World") => {
const font = await load("path/to/some/font");
const { x1, x2 } = font.getPath(text, 0, 0, 12).getBoundingBox();
return x2 - x1;
};
Naturally you'd want to only call load once per font, so you should pull that line out to a higher scope based on your circumstances.
Here's a Code Sandbox comparing this OpenType method to the Canvas and DOM methods:
https://codesandbox.io/s/measure-width-of-text-in-javascript-vctst2
On my machine, for 100 samples each, the typical results are:
OpenType: 5ms
Canvas: 3ms
DOM: 4ms
Another package I found is this one: https://github.com/sffc/word-wrappr
Try this code:
function GetTextRectToPixels(obj)
{
var tmpRect = obj.getBoundingClientRect();
obj.style.width = "auto";
obj.style.height = "auto";
var Ret = obj.getBoundingClientRect();
obj.style.width = (tmpRect.right - tmpRect.left).toString() + "px";
obj.style.height = (tmpRect.bottom - tmpRect.top).toString() + "px";
return Ret;
}
The width and heigth of a text can be obtained with clientWidth and clientHeight
var element = document.getElementById ("mytext");
var width = element.clientWidth;
var height = element.clientHeight;
make sure that style position property is set to absolute
element.style.position = "absolute";
not required to be inside a div, can be inside a p or a span
Building off of Deepak Nadar's answer, I changed the functions parameter's to accept text and font styles. You do not need to reference an element. Also, the fontOptions have defaults, so you to not need to supply all of them.
(function($) {
$.format = function(format) {
return (function(format, args) {
return format.replace(/{(\d+)}/g, function(val, pos) {
return typeof args[pos] !== 'undefined' ? args[pos] : val;
});
}(format, [].slice.call(arguments, 1)));
};
$.measureText = function(html, fontOptions) {
fontOptions = $.extend({
fontSize: '1em',
fontStyle: 'normal',
fontWeight: 'normal',
fontFamily: 'arial'
}, fontOptions);
var $el = $('<div>', {
html: html,
css: {
position: 'absolute',
left: -1000,
top: -1000,
display: 'none'
}
}).appendTo('body');
$(fontOptions).each(function(index, option) {
$el.css(option, fontOptions[option]);
});
var h = $el.outerHeight(), w = $el.outerWidth();
$el.remove();
return { height: h, width: w };
};
}(jQuery));
var dimensions = $.measureText("Hello World!", { fontWeight: 'bold', fontFamily: 'arial' });
// Font Dimensions: 94px x 18px
$('body').append('<p>').text($.format('Font Dimensions: {0}px x {1}px', dimensions.width, dimensions.height));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The Element.getClientRects() method returns a collection of DOMRect objects that indicate the bounding rectangles for each CSS border box in a client. The returned value is a collection of DOMRect objects, one for each CSS border box associated with the element. Each DOMRect object contains read-only left, top, right and bottom properties describing the border box, in pixels, with the top-left relative to the top-left of the viewport.
Element.getClientRects() by Mozilla Contributors is licensed under CC-BY-SA 2.5.
Summing up all returned rectangle widths yields the total text width in pixels.
document.getElementById('in').addEventListener('input', function (event) {
var span = document.getElementById('text-render')
span.innerText = event.target.value
var rects = span.getClientRects()
var widthSum = 0
for (var i = 0; i < rects.length; i++) {
widthSum += rects[i].right - rects[i].left
}
document.getElementById('width-sum').value = widthSum
})
<p><textarea id='in'></textarea></p>
<p><span id='text-render'></span></p>
<p>Sum of all widths: <output id='width-sum'>0</output>px</p>
Rewritten my answer from scratch (thanks for that minus).
Now function accepts a text and css rules to be applied (and doesn't use jQuery anymore). So it will respect paddings too. Resulting values are being rounded (you can see Math.round there, remove if you want more that precise values)
function getSpan(){
const span = document.createElement('span')
span.style.position = 'fixed';
span.style.visibility = 'hidden';
document.body.appendChild(span);
return span;
}
function textWidth(str, css) {
const span = getSpan();
Object.assign(span.style, css || {});
span.innerText = str;
const w = Math.round(span.getBoundingClientRect().width);
span.remove();
return w;
}
const testStyles = [
{fontSize: '10px'},
{fontSize: '12px'},
{fontSize: '60px'},
{fontSize: '120px'},
{fontSize: '120px', padding: '10px'},
{fontSize: '120px', fontFamily: 'arial'},
{fontSize: '120px', fontFamily: 'tahoma'},
{fontSize: '120px', fontFamily: 'tahoma', padding: '5px'},
];
const ul = document.getElementById('output');
testStyles.forEach(style => {
const li = document.createElement('li');
li.innerText = `${JSON.stringify(style)} > ${textWidth('abc', style)}`;
ul.appendChild(li);
});
<ul id="output"></ul>
For any one out there using React and/or Typescript...
Try this Codepen!
export default function App() {
const spanRef = useRef<HTMLSpanElement>(null);
const [textWidth, setTextWidth] = useState(0);
const getTextWidthInPixels = (ref: HTMLSpanElement) =>
ref.getBoundingClientRect().width;
useEffect(() => {
setTextWidth(getTextWidthInPixels(spanRef.current!));
}, [spanRef]);
return (
<div className="App">
<span
ref={spanRef}
contentEditable
suppressContentEditableWarning
onInput={() => setTextWidth(getTextWidthInPixels(spanRef.current!))}
>
Edit Me!!!
</span>
{`textWidth: ${textWidth}px`}
</div>
);
}
It's a good idea to wrap our text in an inline-positioned element (like a <span>)
useRef is the React way to access a DOM element, the <span> in our case
getBoundingClientRect can get the total width of any DOM element.
contentEditable allows users to change the contents of an element ...which is a little unsafe (React will throw warnings!)
suppressContentEditableWarning will help us prevent these warnings
Use scrollWidth on the containing element of the text to get the minimum width of the element including hidden parts due to overflow. More information at https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollWidth
If the element is not in the DOM, add it to some hidden area to do the measurement. For example:
function measureText(text) {
let div = document.createElement("div");
div.innerText = text;
div.style.whiteSpace = 'nowrap';
body.appendChild(div);
let width = div.scrollWidth;
body.removeChild(div);
return width;
}
The style (font-size, weight, etc.) will be inherited by the element and thus accounted in the width. You could also measure the size of more complex content with scrollWidth and scrollHeight.
var textWidth = (function (el) {
el.style.position = 'absolute';
el.style.top = '-1000px';
document.body.appendChild(el);
return function (text) {
el.innerHTML = text;
return el.clientWidth;
};
})(document.createElement('div'));
I guess this is prety similar to Depak entry, but is based on the work of Louis Lazaris published at an article in impressivewebs page
(function($){
$.fn.autofit = function() {
var hiddenDiv = $(document.createElement('div')),
content = null;
hiddenDiv.css('display','none');
$('body').append(hiddenDiv);
$(this).bind('fit keyup keydown blur update focus',function () {
content = $(this).val();
content = content.replace(/\n/g, '<br>');
hiddenDiv.html(content);
$(this).css('width', hiddenDiv.width());
});
return this;
};
})(jQuery);
The fit event is used to execute the function call inmediatly after the function is asociated to the control.
e.g.: $('input').autofit().trigger("fit");
Without jQuery:
String.prototype.width = function (fontSize) {
var el,
f = fontSize + " px arial" || '12px arial';
el = document.createElement('div');
el.style.position = 'absolute';
el.style.float = "left";
el.style.whiteSpace = 'nowrap';
el.style.visibility = 'hidden';
el.style.font = f;
el.innerHTML = this;
el = document.body.appendChild(el);
w = el.offsetWidth;
el.parentNode.removeChild(el);
return w;
}
// Usage
"MyString".width(12);
Fiddle of working example: http://jsfiddle.net/tdpLdqpo/1/
HTML:
<h1 id="test1">
How wide is this text?
</h1>
<div id="result1"></div>
<hr/>
<p id="test2">
How wide is this text?
</p>
<div id="result2"></div>
<hr/>
<p id="test3">
How wide is this text?<br/><br/>
f sdfj f sdlfj lfj lsdk jflsjd fljsd flj sflj sldfj lsdfjlsdjkf sfjoifoewj flsdjfl jofjlgjdlsfjsdofjisdojfsdmfnnfoisjfoi ojfo dsjfo jdsofjsodnfo sjfoj ifjjfoewj fofew jfos fojo foew jofj s f j
</p>
<div id="result3"></div>
JavaScript code:
function getTextWidth(text, font) {
var canvas = getTextWidth.canvas ||
(getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
};
$("#result1")
.text("answer: " +
getTextWidth(
$("#test1").text(),
$("#test1").css("font")) + " px");
$("#result2")
.text("answer: " +
getTextWidth(
$("#test2").text(),
$("#test2").css("font")) + " px");
$("#result3")
.text("answer: " +
getTextWidth(
$("#test3").text(),
$("#test3").css("font")) + " px");
I'm using text-metrics package. Works really nice, I tried this solution but in some reasons, it counts it wrong.
textMetrics.init(document.querySelector('h1'), { fontSize: '20px' });
textMetrics.init({
fontSize: '14px',
lineHeight: '20px',
fontFamily: 'Helvetica, Arial, sans-serif',
fontWeight: 400,
width: 100,
});
Hey Everyone I know I'm a little late to the party but here we go
window.addEventListener("error",function(e){ alert(e.message); });
var canvas = new OffscreenCanvas(400, 50);
var ctx = canvas.getContext("2d");
ctx.font = "16px Ariel"; //this can be dynamic using getComputedStyle
const chars = ["a","b","c","d","e","f"," "," "];
const charWidths = new Map();
while(chars.length > 0){
var char = chars.shift();
var wide = ctx.measureText(char).width;
charWidths.set(char,wide);
}
and then you can use it with something like:
var pixelWidth = charWidths.get("0");
//fyi css properties like letter-spacing need to be accounted for

Categories

Resources