Make text size adjust to fit text in entire container - javascript

My objective is to make my text take as much of the space within a container as possible without overflow. If there are only a few words, they would have a very large font size, inversely if there are several words it would result in a smaller size that still takes as much of the containers area as possible.
So if I had this HTML
<div id="container">
<h1 class="textFill">Make this fit as large as possible in the container</h1>
</div>
and the container was 400 by 300px
#container {
width: 400px;
height: 300px;
border: 1px solid blue;
}
I would want the text to fill the entirety of that space. So far I have this script.
function textFill() {
$(".textFill").each(function() {
var
$text = $(this),
$parent = $text.parent();
var
textW = $text.width(),
parentW = $parent.width(),
ratio = parentW / textW;
var
originalSize = parseFloat($text.css('font-size')),
newSize = originalSize * (1 * ratio);
$text.css("font-size", newSize);
});
}
Here it all is in a http://jsfiddle.net/nz7h2858/41/

I would increase the font size until the element goes beyond its parent's bounds.
Then decrease the font size by one.
textFill();
$(window).resize(textFill);
function textFill() {
var tf= $('.textFill');
for(var i = 1 ; ; i++) {
tf.css('font-size', i);
if(tf.outerHeight(true) > tf.parent().innerHeight() ||
tf[0].scrollWidth > tf.width()
) {
break;
}
}
tf.css('font-size', i-1);
}
Fiddle

http://jsfiddle.net/nz7h2858/42/
This seems to be working a majority of the time. Occasionally some text will go out of bounds, but only slightly. Hopefully it's enough to get you started!
Things to notice:
.textFill {
display: inline;
}
Because h1 is a block element, it defaults to the full width of it's parent. So your ratio for width would always be 1:1.
Secondly, you need to also take into consideration the height. So:
textW = $text.width(),
textH = $text.height(),
parentW = $parent.width(),
parentH = $parent.height(),
ratio = (parentW + parentH) / (textW + textH);

Related

Javascript Font-Resizer Overflowing Div

I've been working on a website (scibowltest.github.io) in which the font-size for an element is determined by javascript. If you go in to the website, it looks fine when displayed on a laptop/desktop with the browser at full width and height. However, if you resize the window to make the width smaller, the font starts to overflow the div in which it is supposed to be contained.
The following code is for the function font-sizer, which determines how big the font-size will be.
function fontSizer(text, box, scale) {
var textID = "#" + text;
var boxID = "#" + box;
var boxHeight = $(boxID).height();
var boxWidth = $(boxID).width();
var fontSize = 0;
if (boxHeight >= boxWidth) {
fontSize = (boxWidth * scale) + "px";
} else if (boxHeight < boxWidth) {
fontSize = (boxHeight * scale) + "px";
} else {}
var textHeight = $(textID).height();
var textWidth = $(textID).width();
if (textWidth > boxWidth) {
fontSize = ((fontSize * (scale * boxWidth)) / (textWidth)) + "px";
} else {}
$(textID).css("font-size", fontSize);
}
The function works based on the smaller dimension of the div (box) containing the text. However, the last if statement tries to compensate for those situations in which the text's width is greater than the div's width to try to shrink the fontsize so that the text's width is equal to the div's width times the scale.
Obviously, from looking at the website, this last if statement isn't working. If anyone could help, I would appreciate it!
For a pure CSS solution you can use some of the new length units that are intended exactly for your usecase - different screen sizes.
Play around with vw,vh,vmin,vmax and see what gives you the best results. I personally use vmin a lot.
It requires a bit of fiddling but would eliminate the use of javascript.
Also I used <wbr> in this example (although it should not be needed) - a "word break opportunity" to additionally prevent overflowing.
div {
width: 40vmin;
font-size: 8vmin;
border: 1px solid red;
resize: both;
text-align: center;
}
p {
width: 40vw;
font-size: 8vw;
border: 1px solid red;
resize: both;
text-align: center;
}
resize the screen to see the fonts scale:
<div>Start/<wbr>Stop</div>
<p>Start/<wbr>Stop</p>

whay can't I change both image height and width at same time with javascript?

I have an image in a div and I want the image to stay centered at all times.
If the width of the image is wider than the screen, then I want the image to expand to the width of the view port. And if the image is shorter than the height of the view port then I want it to expand to the height of the view port.
In my code, when I expand the width, the height expands automatically, which is great since I don't have to calculate it. The height does the same thing. When the height is expanded, the width stays proportional.
However, if the width changes in such a way that the height is now smaller than then view port, then I need to check the height and bring it back up to the view port height (which should expand the width again but it doesn't). When I have to change both height and width at the same time, the automatic proportioning doesn't work. If I do one or the other, it does work.
How can I accomplish this so they can both be changed and work without distorting the image?
my code:
inner_width = $(window).innerWidth();
inner_height = $(window).innerHeight();
if (inner_width < original_pic_width ) {
$(pic).css({'width': original_pic_width});
}
else {
$(pic).css({'width' : inner_width });
}
if (inner_height < original_pic_height){
$(pic).css({'height': original_pic_height});
}
else {
$(pic).css({'height' : inner_height });
}
CSS contain is pretty nice.
$("div").css({
backgroundImage: "url(" + $("img").prop('src') + ")",
backgroundSize:"contain",
backgroundRepeat: "no-repeat"
});
div { width:200px; height:200px; border:1px solid red;}
div img { display:none }
<div>
<img src="http://www.somebodymarketing.com/wp-content/uploads/2013/05/Stock-Dock-House.jpg"/>
</div>
<script src="https://code.jquery.com/jquery-2.2.3.min.js"
integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="
crossorigin="anonymous"></script>
Here is a possible solution (not sure to understand clearly what you want though). Note that I'm not absolutely sure that the centering method is cross-browser.
var div = $("div");
var img = $("img");
var imgw = img.width();
var imgh = img.height();
var imgr = imgw / imgh;
var sizes = [300, 120];
var i = 0;
setInterval(function () {
div.width(sizes[i]);
i = (i + 1) % 2;
adjust();
}, 1000);
function adjust () {
var divw = div.width();
var divh = div.height();
var divr = divw / divh;
if (divr < imgr) {
img.width("100%");
img.height("auto");
} else {
img.width("auto");
img.height("100%");
}
}
div {
position: relative;
}
img {
display: block;
position: absolute;
top: 0; bottom: 0;
right: 0; left: 0;
margin: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:120px;height:120px;border:10px solid #5900CC;">
<img style="width:100%;" src="http://i.stack.imgur.com/jKXi2.jpg" />
</div>
If you set both height and width... both dimensions, height and width will be set.
It should be enough to set just one dimension if you set the width=viewport's width if it's horizontal (width>height) or the height=viewport's height if it's vertical.
Find which dimension you have to change and change that one only. You can do that by checking the difference between the image's width and the window's innderWidth, and the difference between the image's height and the window's innerHeight. Whichever difference is greater is the one you need to change only. That should take care of the other dimension without having to resize both.

Parallax - Offset element(s), tied to scroll

Banging my head trying to sort out the correct logic for adding simple parallax behavior.
I would like to have a number of elements on a page which start out with their top offset a certain distance (e.g. 300px). Then as you scroll down the page, once the top of the element is revealed it will slowly shift upwards (tied to scroll) until the top of element reaches middle of viewport at which time it's top offset is 0 and it remains in place.
I tried using third party script (Scroll Magic, Stellar, etc), but when I couldn't get it right now I'm trying custom code:
https://jsfiddle.net/louiswalch/5bxz8fku/1/
var $Window = $(window);
var offset_amount = 400;
var window_height = $Window.height();
var window_half = (window_height/2);
var sections = $('SECTION.reveal');
sections.each(function() {
var element = $(this);
// Make sure we always start with the right offset
element.css({top: offset_amount});
$Window.bind('scroll', function() {
var viewport_top = $Window.scrollTop();
var viewport_middle = viewport_top + (window_height/2)
var viewport_bottom = viewport_top + window_height;
var element_top = element.offset().top;
if (element_top > viewport_top && element_top <= viewport_bottom) {
var distance_to_middle = (element_top - viewport_middle);
var amount_to_middle = (distance_to_middle / window_half);
console.log(amount_to_middle);
if (amount_to_middle >= 0) {
element.css({top: (offset_amount * amount_to_middle)+ 'px'});
} else {
// ? Lock to end position ?
}
}
});
});
jsBin demo 1. (margin space effect on both enter and exit)
jsBin demo 2. (preserve 0 margin once touched)
Instead of targeting the section elements, (create and) target their first child elements,
otherwise you'll create a concurrency mess trying to get the top position but simultaneously modifying it.
Also, you cannot rely on fixed 300px margin (i.e: if window height is less than 500px, you're already missing 100px). That space can vary when the screen height is really small, so you also need to find the idealMarg value.
var $win = $(window),
$rev = $('.reveal'),
winH2 = 0,
winSt = 0;
function reveal() {
winSt = $win.scrollTop();
winH2 = $win.height()/2;
$rev.each(function(i, el){
var y = el.getBoundingClientRect().top,
toMiddleMax = Math.max(0, y-winH2),
idealMarg = Math.min(300, toMiddleMax),
margMin = Math.min(idealMarg, idealMarg * (toMiddleMax/winH2));
$(">div", this).css({transform: "translateY("+ margMin +"px)"});
});
}
$win.on({"load resize scroll" : reveal});
*{box-sizing:border-box; -webkit-box-sizing:border-box;}
html, body{height:100%; margin:0;}
section > div{
padding: 40px;
min-height: 100vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
<div style="background-color:red">1</div>
</section>
<section class="reveal">
<div style="background-color: yellow">2</div>
</section>
<section class="reveal">
<div style="background-color: orange">3</div>
</section>
<section class="reveal">
<div style="background-color: pink">4</div>
</section>
I've used in HTML just a <div> logically, that has to be the one and only first child of a section parent.
You're welcome to tweak the above code to make it more performant.
Hey so here is my go at an awnser.
http://jsbin.com/wibiferili/edit?html,js,output
The jist of it is as follows.
JS
var $Window = $(window),
parallaxFactor = 2;
$('.parallaxblock').each(function(a,b){
var element = $(b);
element.css("top",element.data("pOffset") + "px");
$Window.bind('scroll', function() {
var pos =
// Base Offset
element.data("pOffset")
// parallaxFactor
- ($Window.scrollTop() / parallaxFactor);
pos = pos < 0 ? 0 : pos;
element.animate({"top": pos + "px"},10);
return;
});
});
Styles
body{
height: 4000px;
}
.parallaxblock{
position:fixed;
background:#999;
opacity:.5;
}
Example Usage
<div class="parallaxblock" data-p-offset=100>Im A Block</div>
<div class="parallaxblock" data-p-offset=200>Im Also Block</div>
<div class="parallaxblock" data-p-offset=1500>Im Another Block</div>
So by checking the offest its never lower then 0 we can lock it at the top of the screen once it reaches it.
I get the offset amount of the data tag on the div.
If you wanted to change the rate of scroll in different posistions you could change the parallax factor at a certain percentage of screen height.
Hope this helps.

Resizing a web page dynamically

I am developing a bunch of small web applications that have an unknown window size as target. To solve this problem, I am developing very large layouts and scaling them according to the window size.
My solution however has an inconvenience. When I resize everything, things get a little bit out of place (mainly when scaling text) and it is noticeable. My code is very simple, everything in my page is absolutely positioned so I just get the scaling factor and apply it to all the positions and width / height of every div/img/span/input in the page. The code is as follows:
function resize()
{
var wh = $(window).height();
var h = maxHeight;
var ww = $(window).width();
var w = maxWidth;
var wProp = ww / w;
var hProp = wh / h;
if (wProp < hProp) prop = wProp;
else prop = hProp;
if (prop > 1) prop = 1;
console.log(prop);
$("div").each (applyNewSize);
$("img").each (applyNewSize);
$("span").each (applyNewSize);
$("input").each (applyNewSize);
}
//this is run when the page is loaded
function initializeSize (i)
{
this.oX = $(this).position().left;
this.oY = $(this).position().top;
this.oW = $(this).width();
this.oH = $(this).height();
if ($(this).css("font-size") != undefined)
{
this.oFS = Number($(this).css("font-size").split("px")[0]);
}
}
function applyNewSize (i)
{
if (this.oFS != undefined) $(this).css("font-size", Math.round(this.oFS * prop) + "px");
$(this).css("left", Math.round(this.oX * prop) + "px");
$(this).css("top", Math.round(this.oY * prop) + "px");
$(this).width(Math.round(this.oW * prop));
$(this).height(Math.round(this.oH * prop));
}
This problem has been tormenting me for the past week. Do you have any workaround or solution for this?
I recommend you to read about Responsive Web design.
It works putting % instead the exact pixels :
<div class="container">
<section>
THIS IS THE SECTION
</section>
</div>
CSS::
.container{
width: 80%; // 80% instead pixels
background: gainsboro;
border: 3px inset darkgrey;
height: 200px;
margin:auto;
text-align:center;
}
section{
width: 80%; // 80% instead pixels
height: 80%; // 80% instead pixels
background: darkgrey;
margin:auto;
}
Then you can use media queries as well, to reallocate the blocks or applying different styles on different widths :
example tutorial : http://css-tricks.com/css-media-queries/

Checking a text element's width (based on font-size) against its parent container

I come to you with a tricky question:
Imagine you have the following basic structure:
<div><p>hello</p></div>
Now assume that div has display:block; and width:200px;.
Using javascript, how would you check what font-size gives you a 'hello' as big as possible without horizontal overflow (in the case of one word) or jumping to a 2nd line in case of a sentence or group of words?
I can't think of a way to measure the space occupied by text so that it can then be checked against that of the parent container, let alone checking if an element is overflowing or linejumping.
If there is a way, I'm sure this is the right place to ask.
Take a look at FitText
It is open source on github as well.
If you are interested in typography you might want to check out their other project called Lettering.js
There may be a method that's not as crazy, but this should be as precise as possible. Essentially, you have a div that you use to measure its width and incrementally increase the text content until it exceeds the width of the target div. Then, change the target div's <p>'s font size to the measuring div's minus 1:
http://jsfiddle.net/ExplosionPIlls/VUfAw/
var $measurer = $("<div>").css({
position: 'fixed',
top: '100%'
}).attr('id', 'measurer');
$measurer.append($("<p>").text($("p").text()));
$measurer.appendTo("body");
while ($measurer.width() <= $("#content").width()) {
$("#measurer p").css('font-size', '+=1px');
console.log($("#measurer").width());
}
$("#measurer p").css('font-size', '-=1px');
$("#content p").css('font-size', $("#measurer p").css('font-size'));
$measurer.remove();
Quick and dirty
fiddle
Set p's style to display: inline then run this
var dWidth = $("div").width();
var pWidth = $("p").width();
var starting = 1;
while (pWidth < dWidth) {
$("p").css("font-size",starting+"em");
pWidth = $("p").width();
starting = starting + .1;
}
Try this:
Auto-size dynamic text to fill fixed size container
(function($) {
$.fn.textfill = function(options) {
var fontSize = options.maxFontPixels;
var ourText = $('span: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);
return this;
}
})(jQuery);
$(document).ready(function() {
$('.jtextfill').textfill({ maxFontPixels: 36 });
});
<div class='jtextfill' style='width:100px;height:50px;'>
<span>My Text Here</span>
</div>
new jsFiddle Demo (updated 3/22/13)
I would just keep increasing the font size until the clientWidth or clientHeight changed. However, this becomes unreliable when using the actual element itself. To handle that situation, it is possible to create a span on the fly and then monitor the span's dimensions in order to properly retain the actual element's original sizes.
js
var adjuster = document.getElementById("adjust");
adjuster.onclick = function(){
var p = document.getElementById("p");
var text = p.innerText;
var s = document.createElement("span");
s.innerText = text;
p.innerHTML = "";
p.appendChild(s);
var h = p.clientHeight;
var w = p.clientWidth;
var size = 10;
while(true){
size++;
s.style.fontSize = size + "px";
if($(s).height() > h || $(s).width() > w){
size-=2;//rollback to no height change
s.style.fontSize = size + "px";
break;
}
}
p.style.fontSize = s.style.fontSize;
p.removeChild(s);
p.innerText = text;
};

Categories