I am developing an application where i have to display names of users in following structure :
In above structure, in the name field, it may exceed the right border of the outer <div> tag, i want to cut the name value just before it touches the right border and append the a string '...' in the end just like below
How can i make it work for UTF-8, unicode or Normal english letters in the name field?
P.S. I m using PHP for server side processing.
The easiest way is to set some CSS on that div...
<div style="white-space:nowrap; text-overflow:ellipsis;">Er. Christopher Allen (ChristAllenMoreTextMoreText)</div>
You have to set the white-space attribute as well, otherwise you won't ever get to this elipsis point. You should also probably set overflow:hidden.
Big caveat though! This does not work in all browsers. IE7 and beyond, Safari/Chrome, are all fine. I believe there are issues with it in Firefox though.
Edit: Here is a Firefox workaround. Not amazing though.
Since you can't know the exact width of the container on the client side (in the user's browser), you must use Javascript for this.
You can't just let it wrap?
Perfecting a server-side character limiter so it cuts off just before the line-end will be tough, if not impossible, unless using a monospace font. And you can't account for the user's browser settings, so the solution will always be flawed. If any character limiter is created, it will need to be client-side.
What about setting overflow: hidden on the name element?
I personally do mine on the back-end with PHP using the following custom function:
function trunc($string, $limit, $break=" ", $pad="...") {
// return with no change if string is shorter than $limit
if(strlen($string) <= $limit) return $string;
$string = substr($string, 0, $limit);
if(false !== ($breakpoint = strrpos($string, $break))) {
$string = substr($string, 0, $breakpoint);
}
return $string . $pad;
}
Sure, it's not terribly schnazzy, and it doesn't exactly auto adjust, but my project requirments demand that everything works 100% correctly in IE6 and this works without fail.
If you HAVE to do it on the front end, try 3 dots: http://tpgblog.com/threedots/
As Brad suggested: CSS is the way to go. Flexible presentation is better handled on the client side. However, most browsers do not implement this specific CSS3 feature (yet). In the meantime you could try one of these jQuery (javascript) plugins that makes the same functionality available to all browsers.
http://plugins.jquery.com/plugin-tags/ellipsis
http://plugins.jquery.com/project/shorten
http://plugins.jquery.com/project/ThreeDots
http://plugins.jquery.com/project/text-overflow
http://plugins.jquery.com/project/AutoEllipsis
Are you using a database? If so you can write a conditional statement to check if the name is over a certain length and if so append ...
You might want to define your width in Em and then count characters PHP side to approximate where you need to cut and append your ellipses.
In effect you need to work out the pixel length of the string and keep chopping chars until it falls below the threshold. I could explain that on the server side if you had .net at hand, but you dont, so maybe a this javascript might help on the client : Truncate a string nicely to fit within a given pixel width
Related
I am sure you guys must have seen that font resizing option on some website where they display alphabet "A" in small, medium and large sizes clicking on which changes the font size of website. I have two questions:
What is that thing called actually? Like if there is a term to describe it?
What arguments can I give against using this on website? One of the client has asked to incorporate it in website and I don't see any real benefit in using it so what arguments can I give to client against using it?
It is called "font size change options", or "font resizer".
Here is a simple and minimal 5 lines of code jQuery tutorial: http://www.programming-free.com/2013/12/increase-decrease-font-size-jquery.html
A bit of the code that enlarges the font size:
newFontSize= parseInt($('#content').css('font-size')) + 2;
$('#content').css('font-size', newFontSize);
The user could just use CTRL+ in browser. The problem is that the final user doesn't know this trick.
This is a fast and simple implementation, no need to convince the client against it. I find myself getting hard to see clear small text after 10 hours of programming. Maybe the client has sight problems and needs to address others like him.
"As of jQuery 1.6, .css() accepts relative values similar to .animate(). Relative values are a string starting with += or -= to increment or decrement the current value. For example, if an element's padding-left was 10px, .css( "padding-left", "+=15" ) would result in a total padding-left of 25px."
Reference
So to do that you can use a function callback which will return the actual value, then you return the new value.
Like the following.
$("#fontPlusBtn").click(function (){
$("#textDiv > *").css("font-size", function(i, value) {
return parseInt(value) * 1.1;
});
});
Working Demo for Increasing Font Size on Button Click:
I hope this helps you as you described font size change on Button Click.
What is the target group of your client? Adding such feature is generally considered good practice of web accessibility. It doesn't really take up too much space on the screen and doesn't mess with the design but gives users the options to enlarge the text in case they are having troubles reading the text.
I wouldn't try to argue against it but instead find a neat way to implement the functionality.
BBC's accessibility policy is a good read: http://www.bbc.co.uk/accessibility/best_practice/policy.shtml
I need to determine minimum width adequate for displaying a possibly wrapped dynamic HTML string. Without word-wrapping this is simple: create a span, set its innerHTML and read offsetWidth. However, I'm not sure how to force linebreaks... Easiest incomplete approach I see is to replace all spaces by <br/>, but lines can be wrapped not only on spaces but also e.g. on hyphens.
So, basically, I want a browser to lay out sth. like
Max.
word-
wrapped
string
<----->
somewhere off-screen to measure width of the longest contained word. Is there a generic way to do that?
EDIT
I.e., for no line wraps:
function computeWidth (str) { // code to make it off-screen and caching omitted
var span = document.createElement ('span');
document.body.appendChild (span);
span.innerHTML = str;
return span.offsetWidth;
}
How would I write a similar function which forces line breaks on str, presumably playing with span.style?
You can use CSS work-break / word-wrap and programmatically inserted soft-hyphens (, but I'd advise you to read up on cross browser problems regarding soft hyphens, as there are quite a few - I normally us the unicode for a soft hypen (U+00AD), but your mileage may vary), and then determine the width with javascript using the range object and measuring cursor offset from the left.
I'm suggesting the use of soft-hyphens, because even the same browser will normally break words differently depending on the OS / which dictionary (on OSX) is used. If that's not an issue for you, you can do it without soft hyphens.
Afaik there is no generic way to get what you want in html/js (it's different if you were using something like flash).
Range object:
https://developer.mozilla.org/en-US/docs/Web/API/range
A different approach would be using the canvas object, but you would probably not get exact results there, as there is just too much factors influencing text rendering in browsers nowadays (font, size, kerning, tracking, ...)
Again another approach would be using <pre> tags / whitespace: pre-wrap, setting the font to what you normally use, and then either emulate breaking words by inserting linebreaks or copying them from still another span/div/whatever set up with word wrap - I haven't tested this yet, but if it works, it might be easer than iterating with the range object.
Edit: Just so it's not only in the comments, still another solution:
Start your container with width 1px, then increase the width, checking the height every time ; when the height decreases, go back one step, and you got your width. Simplest implementation would use 1px increase/1px decrease, but you could of course optimize it to using something like a binary search algorithm, e.g. starting with 1px, then 2px, then 4px increases, then the same backwards, and forwards again and so on till you have a result at a 1px step. But that's only if the 1px inc/dec sollution is too slow ;)
Use the CSS word-break rule:
The word-break CSS property is used to specify how (or if) to break lines within words.
Normal
Use the default line break rule.
break-all
Word breaks may be inserted between any character for non-CJK (Chinese/Japanese/Korean) text.
keep-all
Don't allow word breaks for CJK text. Non-CJK text behavior is same as normal.
<p style="word-break:break-all;">
Max.word-wrapped string<----->
</p>
(source)
Try to play with the word-break Property.
More here: http://www.w3schools.com/cssref/tryit.asp?filename=trycss3_word-break
You should try:
word-break: break-all;
Add it to the CSS like in this fiddle, or read here.
I have a set of HTML codes and I am wondering how can I wrap a code such that it is interpreted correct by the browser and independent of the others.
I think I should give an example:
x = <a href="stackoverflow.com">Something
y = <b>Else</b>
I print x, then y and the browser will consider that y is part of the link defined in x. How can I force the browser to interpret x independent of y; that's is, how can I wrap x and y?
I don't know if it is relevant, but I work in Python.
Thanks!
Close the anchor tag if you don't want the bold tag to be part of it.
x = Something
If you don't close the anchor, most browser will assume that the rest of the document is contained within this tag.
Also, could I recommend that you use <strong> instead of <b> since <b> is not semantic.
Modern browsers do a good job of "cleaning up" broken or invalid HTML code. Obviously though there are lots of situations where what the author intends is not what the browser interprets. Your example is a good one: where should the browser insert the closing </a> tag? The browser has internally a bunch of rules to decide where to do this (which in your case doesn't give you what you want).
The only way to reliably get a browser to render exactly want you want is to ensure that what you are sending to the browser is correct! In that case, look at your HTML strings independently and add missing end tags where needed.
(Depending on the complexity of the HTML, there's possibly a number of approaches to this. You might be able to get away with manually checking each string, or if the HTML is more complex, you might need to use a parser.)
You must find all the tags in the HTML snippets and make sure that they are closed properly.
A simple solution is to use this regexp: r<[^>]+> and this pseudocode:
find next match:
if match ends with `/>`:
continue
if match starts with '</':
Pop element from stack and make sure that the name matches the element from the match
else:
Push element name on stack
for each element on stack:
print '</%s>' % element.name
If I have a flowing layout (position: static / relative), does the browser store the calculated coordinates (x,y) of a div in properties which can be accessed?
Further, it would suffice if the solution worked with Firefox only. JQuery is unfortunately, not an option.
In 'native' JavaScript you can do it like that:
document.getElementById('yourElement').offsetLeft
document.getElementById('yourElement').offsetTop
but you'd probably need to add up few offsets of parent elements depends what position is applied.
It does indeed. Unfortunately it's pretty difficult to get that information out reliably due to browser inconsistencies and general ugliness of raw DOM access.
I suggest jQuery, where you might have code like:
$('#some_div').offset().top
Which will give you the y position of the div from the top left of the document.
No, however using mootools (and probably jquery) you can say $(element).getLeft() or $(element).getTop().
or you could use something like this:
function getLeft(obj) {
return (obj.offsetParent==null ? obj.offsetLeft : obj.offsetLeft + getLeft(obj.offsetParent));
}
function getTop(obj) {
return (obj.offsetParent==null ? obj.offsetTop : obj.offsetTop + getTop(obj.offsetParent));
}
In actionscript 3, my TextField has :
CSS styling
embedded fonts
textAlign : CENTER
autoSize : CENTER
... when italics are used the very right character gets slightly cut off (specially caps).
It basically seems that it fails detecting the right size.
I've had this problem before but just wondered is there a nice workaround (instead of checking textWidth or offsetting text etc.)?
Initialize your textField as you always do, using multiline, autosize, htmlText...
Then do this little trick :
// saving wanted width and height plus 1px to get some space for last char
var savedWidth = myTextField.width + 1;
var savedHeight = myTextField.height + 1;
// removing autoSize, wich is the origin of the problem i think
myTextField.autoSize = "none";
// now manually autoSizing the textField with saved values
myTextField.width = savedWidth;
myTextField.height = savedHeight;
Not that it is much comfort to you, but Flash sometimes has trouble with this seemingly simple task. CSS styling of html TextField was a nice addition but it has caused headaches for text-rendering. In fact I very rarely use CSS for styling text for that reason. I can only imagine that combining bold, italic and normal type faces within the HTML causes Flash to get some of the width calculations wrong which causes autoSize to set the mask a tiny bit short. I hope very much that the new text rendering engine in Flash Player 10 will finally fix these issues (it certainly looks better in theory).
So my solution is never to use HTML with the exception being when I require <a> links in my text ... and there are even some tricky text shifting issues there. In those cases I avoid mixing different font weights and font styles within the same text field. All other cases I use TextFormat directly on TextField.
I suppose if you can't get out of your current architecture (for some reason) you could try adding to the end of your html encoded strings. Or you could manually set the width of the field and not rely on autoSize (as you have mentioned). But if you keep on the CSS/HTML route you may find another new and painful limitation just when you don't want it.
I've had issues with TextField masks behaving differently in the Flash preview, and in the actual browser plugin. Usually, and this is strange to me, it would appear more correctly in the browser. Have you tried running the swf in a browser to see if the problem is actually an annoyance rather than a permanent problem?
I had said this:
My in-ideal approach to solving this is to attach a change event to the TextField which always adds a space after the last character of the field. And then to remember to trim this space off when using the value.
But that didn't take into account that this probably doesn't have a change event and that it's an HTML rendered text field. To add a trailing space in the HTML text field throw in an again, that's not really fixing the problem.