Basicly I want a text to resize depending how long the text is. If I wrote "WWWWWWWW" it would be resized to fit inside the 100px div.
If i wrote "Test" it wouldn't be resized because it wont break the 100px limit.
I'm sure you get the idea by now.
I'm open for anything. Javascript, php, whatever you have to offer.
I think javascript is your friend here, as it allows you to best fit the text regardless of the user's browser window size (if you do it in PHP and oversize/the layout will break for certain users).
I had a similar issue, which made me write my own plugin for this. One solution is to use the shrink-to-fit-approach, as described here.
However if you have to fit multiple items or are concerned with performance, e.g., on window resize, have a look at jquery-quickfit.
It meassures and calculates a size invariant meassure for each letter of the text to fit and uses this to calculate the next best font-size which fits the text into the container.
The calculations are cached, which makes it very fast (there is virtually no performance hit from the 2nd resize on forward) when dealing with multiple texts or having to fit a text multiple times, like e.g., on window resize.
Demo for a similar situation as yours
Further documentation, examples and source code are on the project page.
if you use a font that has a fixed width(i.e. all letters are equal width) then you can do this using php or javascript.
count the number of letters in php using strlen. then hard code the font size e.g. this example is showing how it can be done and is not the best way to do. Let me know if you have any questions.
code didnt work properly
but
if(strlen($text)>5){
$fontsize = 11px;
}
etc...
Do something like this in PHP:
$length = strlen($string);
if($length < 5)
{
$added_class = 'short';
}
elseif($length < 10)
{
$added_class = 'medium';
}
else
{
$added_class = 'long';
}
echo '<div class="normal_class '.$added_class.'">'.$string.'</div>';
And in your CSS file:
div.short { font-size: 15px }
div.medium { font-size: 13px }
div.long { font-size: 10px }
Related
I know this question is asked multiple times, yet mine is different. I noticed that with the pure JavaScript solution, there is a need to resize the screen, while mine has absolutely nothing to do with resizing a screen.
What I have is a container div with some text in it. All texts have a certain font-size, but I want to change the font-size whenever the text gets a certain length.
I have seen this solution on SO:
Resize font depending on string length
Yet, this absolutely looks horrible in pure JavaScript and it's a post of three years ago. There surely must be a better (shorter, better) solution for this. I have read about the CSS solutions, but as I said: I am not using a certain viewport and I don't want to. I just want to change the font-size when it's too long.
I have made a JSFiddle to illustrate the problem:
https://jsfiddle.net/tpx71aqL/
<div class="test">
Blablabla
</div>
<div class="test">
Blablabla12124e121211asdasasas
</div>
PS: I can't use jQuery and don't want to use ellipsis.
An idea for this solution is actually really simple. Check out my codepen here.
Using a simple while loop which checks clientWidth against scrollWidth which you can learn more about here, we use the javascript .style.fontSize = "smaller" which decreases the font size by 1 unit. This works well when we don't know what unit is assigned in the CSS. You can read more about it here.
Hope this helps.
document.onreadystatechange = () => {
if (document.readyState === 'complete') {
var container = document.getElementById("test");
while (container.scrollWidth > container.clientWidth) {
container.style.fontSize = "smaller";
}
}
};
.test {
width: 200px;
border: 1px solid black;
font-size: 16px;
}
<div class="test">
Blablabla
</div>
<div class="test" id="test">
Blablabla12124e121211asdasasas
</div>
This fiddle shows what I suggested in my comment. You extract the current width of the text wrapper and reduce font size until you have a wrapper the same size or slightly smaller than the parent.
var fit = document.getElementById("fit"),
wrap = document.getElementById("wrap"),
step = 0.5,
currentSize;
while (fit.offsetWidth < wrap.offsetWidth) {
currentSize = parseFloat(window.getComputedStyle(wrap, null).getPropertyValue('font-size'));
wrap.style.fontSize = (currentSize - step) + "px";
}
Note the getComputedStyle to really get the calculated size.
You could improve this by making the reduction step smarter, instead of just going down a step again and again; for example calculate how far a 1px reduction approximated the wrapper width to the parent width and adjust step size accordingly.
Also this does assume that the text indeed needs scaling down, no scaling up - the same idea applies.
I needed something similar and I ended up doing something like this:
var elem = document.getElementById("test");
elem.style.fontSize = 30 - elem.innerHTML.length / 6 + 'px';
The idea is to set the max size and reduce it based on the length of the string.
Not fancy or sophisticated but worked for me.
I am a skilled database / application programmer for the PC. I am also an ignorant html / javascript / web programmer.
I am creating some documentation about some .Net assemblies for our intranet. Ideally I would like to display an image full size if the browser window can fit it. If not then I would like to reduce it and toggle between a small version and full size version by a click. It is a dependency chart and can be different sizes for different pages. I would prefer a single function to handle this but being it is for our use none of the requirements I mentioned is set in stone. I would like to make it work well but nothing is mandatory.
I read a lot of stuff but couldn't find anything that matched what I wanted. First I tried this (after a few iterations):
<img src='Dependancy Charts/RotairAORFQ.png' width='100%' onclick='this.src="Dependancy Charts/RotairAORFQ.png";this.width=this.naturalWidth;this.height=this.naturalHeight;' ondblclick='this.src="Dependancy Charts/RotairAORFQ.png";this.width="100%";'>
It has problems. First off it enlarges a small image and it looks funny. Second I would have to put the code in every page. Third it requires a double click to restore it. I was going to live with those short commings but the double click fails. I can't figure out how to restore it.
So I tried to get fancy. I couldn't figure out how to get past problem 1, but solved 2 and 3 by creating a function in a separate file. Then I ran into what appeared to be the same problem. This was my second attempt:
function ImageToggle(Image)
{
if (ImageToggle.FullSize == 'undefined')
ImageToggle.FullSize = false;
if (ImageToggle.FullSize)
{
Image.width='100%';
ImageToggle.FullSize = false;
}
else
{
Image.width=Image.naturalWidth;
ImageToggle.FullSize = true;
}
return 0
}
And in my page:
<img src='Dependancy Charts/RotairAORFQ.png' width='100%' onclick='ImageToggle(this)'>
Can what I want be done? It doesn't sound impossible. If it is a large amount of effort would be required then alternate suggestions are acceptable.
You're probably interested in the max-width: 100% CSS property, rather than a flat-out width:100%. If you have a tiny image, it'll stay tiny. If you have a huge image, it gets resized to the width of the containing element.
For example: http://jsbin.com/kabepo/1/edit uses a small and a huge image, both with max-width:100%. As you can see, the small image is untouched, the huge image is resized to something sensible.
I would recommend that you set a the max-width: 100% CSS property for the image.
This will prevent the image's width from expanding to be greater than the container's width.
You can also do the same with max-height: 100% if you are having problems with the image overflowing vertically.
Please see this JSFiddle for an example.
(Note: If you set both a width and a height attribute on the <img> tag directly or in your CSS file your image will not be scaled proportionally.)
Does it have to be a toggle or would a mouseover work for you as well?
<style>
.FullSize { width:100px; height:auto; }
.FullSize:hover { width:90%; height:auto; }
</style>
<img src="Dependancy Charts/RotairAORFQ.png" class="FullSize">
Note: when image is made larger IN the page - the surrounding content will be displaced around it - depending on how you have set up the layout.
Also if you have any body margins or table or div paddings, using image width at 100% will make the page scroll. To check just change 90% to 100% and work your way up / down.
You could also force the image to be a specific size until the browser gets made smaller by the user / has a smaller resolution.
<style>
.FullSize {width:1000px;max-width:100%;height:auto;}
</style>
<img src="Dependancy Charts/RotairAORFQ.png" class="FullSize">
A tip: the image used must be the largest one. So minimum width of lets say 1200 pixels wide (if that is the forced image size you use). That way regardless of size it is it will remain clearer than a small image becoming a large. Since it's an intranet, file size shouldn't be an issue.
Thanks all for your help. Rob and Mike both pointed me to an excellent solution. I now have my page load with an image that fits the browser window, resizes with the browser and if the user is interested they can expand the image and scrollbars appear if necessary. I got this to work in a function so minimal code is needed for each page.
To load the image:
<p style="overflow:auto;">
<img src='Dependancy Charts/RotairAORFQ.png' width="100%" onclick='ImageToggle(this)'>
</p>
And the function:
function ImageToggle(Image)
{
if (ImageToggle.FullSize == 'undefined')
ImageToggle.FullSize = false;
if (ImageToggle.FullSize)
{
Image.style="max-width: 100%";
ImageToggle.FullSize = false;
}
else
{
Image.style="max-width: none";
Image.width=Image.naturalWidth;
ImageToggle.FullSize = true;
}
return 1
}
if you want to get current browser window size and if you want to do it on a click event so try this in jquery or javascript:
<script>
$("#myButton").click(function(){
var x = window.innerHeight; // put current window size in x (ie. 400)
});
</script>
I am trying to create/invent a new javascript slider object which will work by displaying a base line image:
http://imgur.com/DuVkE.png
then I want to use these 'knobs' to layer on top depending on certain circumstances
http://imgur.com/GKkqx.png
These have already been 'cut up' and will be placed on one of the three black knobs. I have many different colors because I plan to run through them so that the color appears to transform from one, to the other.
So I need to be able to attach an image to the id I received from the user and then manipulate the image later.
My code:
<div id='option1'></div>
<script type="text/javascript">
var slide1 = new slider("option1");
My constructor will look something like this:
function slider(id) {
var obj = document.getElementById(id);
if (!obj) {
var state = -1;
return -1;
}
var state = 0; //blank state
//alert("in");
//alert(document.getElementById(id).className);
//this.addClass("hSliderBack"); INCORRECT SYNTAX!!!
$("#"+id).addClass("hSliderBack"); //this works
}
I fixed the problem with the addClass above, though a little ugly.
My CSS script:
.hSliderBack
{
background-image: url('/Switches/switchLine.png');
background-repeat: no-repeat;
padding-left: 2px; /* width of the image plus a little extra padding */
display: block; /* may not need this, but I've found I do */
}
This is how I can add a picture to my constructor. Still a lot of work to do, but at least it's a start. Any comments are still appreciated as I am very green!!
What you write here:
//obj.innerHTML = "<img src=' this doesn't seem right to me.
is in fact one perfectly reasonable and viable way. You enter into the DOM the <img> node referencing the image you want to display.
However, more common and perhaps more maintainable solution in many cases is to have a CSS style that references a background image, and you enter a <div> into the DOM using the style that causes your image to be displayed.
You should ask yourself, though, is it best to do this without any support from tools. Many of the most popular JavaScript libraries have tools like this built in, or at the very least, have methods that make building this type of code much, much easier.
Of course, if you are doing this to learn the basics of web development before using a framework so you understand what they are doing more thoroughly, more power to you :-)
I was thinking about how to make some cool image effects in browser, and I know it may be a little late to be heading down this train of thought with HTML5/CSS3 up and coming, but I was wondering what the inherent limitations / problem points there would be with implementing a library that essentially created divs each to hold a pixel of an image using background offsets. It is clear that this will create many divs, but if you wanted to work with only rows or columns on a small image it doesn't seem like this would be that unreasonable. With browser caching images, a request wouldn't have to be made for every segment, and the only other potential problem I can see is the processing of the positioning, which I imagine won't be a problem. I don't really have anything at this point to stop from going forward playing with images like this (so I will!), but I'm curious if there is anything that I am overlooking here that would make the idea unfeasible, and especially anything tricky I should be aware of. Thanks :)
Edit: Tried this, and it seems like there is either an inherent problem or a problem in my code (sorry it sucks, was just playing around), use with any image and you will see the difference.
var lpath = "images/logo.png"
window.onload = function(){
console.log('test');
$('body').append("<img id='logo' style='display:none' src="+lpath+">");
console.log($('#logo').width());
console.log('hello');
var logod = $('<div></div>')
.addClass('i')
.width($('#logo').width())
.height($('#logo').height())
.css('background-image','url('+lpath+')')
$('body').append(logod);
for(var i = 1; i <= $('#logo').height(); i++){
var cons = $("<div></div>")
.height(1)
.width($('#logo').width())
.css('background','url('+$('#logo').attr('src')+') no-repeat 0 ' + (-i));
$('body').append(cons);
}
}
Image on the top is just an , image on the bottom is a series of 1px tall divs.
PS Has to do with browser zoom.
It could be very slow. If you are clever you can split only as much as necessary, so there are fewer divs for the browser to deal with. I'm sure you could do it though and it might be fun.
I want to auto-generate a HTML table from some custom data. One of the columns in my data is a number in the range 0-100, and I'd like to show it in a more graphical way, most desirably a colored horizontal bar. The length of the bar would represent the value, and the color would also change (i.e. below 20 it's red, etc.)
Something like this (created with paint.net):
(source: thegreenplace.net)
One way this can be achieved is by generating an appropriate .PNG and placing it there as an image. But I think that it can probably be done with some concoction of HTML/CSS/Javascript in an automatic way (i.e. the values thrown into the table are numeric, and JS converts them to bars before showing).
Perhaps someone has done something like this already and can share?
Thanks in advance
P.S: If it can work in IE6, that would be best (don't ask...)
P.P.S: It should work offline, so existing webservices (like Google charts) won't help
AListApart has a great article on how to generate charts using purely CSS. It's nice because it is accessible, meaning even without CSS it will provide meaningful data.
http://www.alistapart.com/articles/accessibledatavisualization
Update: According to one of the commenters on this answer, this solution will also work in IE6.
This is doable.
2 options:
1) put an image in every cell using the img tag and resize the image using the width attribute
2) put a div with a pre-set height and change the width according to the value you want it to display. Use the background color of the div as your color - no images needed.
example:
<table style="border: 1px solid black">
<tr><th>name</th><th>value</th></tr>
<tr><td>hi</td><td><div style="height: 10px; width: 35px; background-color: #236611">35</div></td></tr>
<tr><td>yes</td><td><div style="height: 10px; width: 15px; background-color: #236611">15</div></td></tr>
<tr><td>see?</td><td><div style="height: 10px; width: 75px; background-color: #2366aa">75</div></td></tr>
</table>
... you could/should tweak the sizes to look nicer of course :-)
The best way is the second part of simon's post. Place a div wherever you need it and change the width with javascript or PHP (depending on if you want it to dynamically change or not) using percentages. Use an if statement for the color. For ex, in javascript:
function displayGraph(barID, number)
{
var color;
if (number <= 20)
{
color = "red";
}
elseif (number > 20 && number <= 60)
{
color = "yellow";
}
else
{
color = "green";
}
var bar = document.getElementById(barID);
bar.style.width = number + "%";
bar.style.backgroundColor = color;
}
I didn't test this exactly, but something like it should work.
Check out the jQuery Sparkline which provides inline charts, similar to what you are looking for. If you use a bullet graph, you can display the good/normal/bad ranges associated with your data which provides a huge amount of data in a very small space.
Since you already have your data in a table, you might check out the jQuery Visualize Plugin. Once you include it, you'd just call something like:
$('table').visualize();
and it builds a graph from your table.
If you want it to work offline as well, maybe flot can be used.
It is based on canvas and jquery.
I haven't used it yet but it's on my todo list.
The sample code seems simple enough:
$(function () {
var d1 = [[0, 3], [4, 8], [8, 5], [9, 13]];
$.plot($("#placeholder"), [ d1 ]);
});
It's not HTML, but have you looked into Google Charts? It's really quite amazing.
http://code.google.com/apis/chart/