Truncating html text appropriately into a fixed size area - javascript

In a generated html page, we have a fixed size area (lets say 200 x 300) in which we need to fit in as much text as possible (like a regular paragraph of text), and if it doesn't fit, remove an appropriate number of characters and append "..." to the end.
The text is NOT in a fixed sized font, and although we are using one specific font for this text, a "generic" solution would obviously be preferred.
This looked interesting, but I'm thinking it would be very slow with this function being called for several items on a page - http://bytes.com/topic/javascript/answers/93847-neatly-truncating-text-fit-physical-dimension
The solution can use an intermix of html, css, js, and php as needed.
Suggestions on approaches are more than welcome!

I'd say that the solution you found is the best. It is, for instance, used for this jQuery plugin which autoresizes textareas as you enter text into it. I took the concept and rewrote it with jQuery for this simple test here: http://jsfiddle.net/ZDr5K/
var para = $('#para');
var height = 200;
while(para.height() >= height){
var text = para.text();
para.text(text.substring(0, text.length - 4) + '...');
}
Possible improvements would include right trimming and removing the period if the last character is a full stop. Removing word by word would also be more readable/slightly faster.
As for the function running multiple times, that would be unavoidable. The only thing you can really do with CSS here is to use :after to append the ellipses, but even that should be avoided for cross-compatibility problems.

Set the element dimensions via CSS and its overflow to "hidden".
Then, find out with this function, if the element's content is overflowing (via):
// Determines if the passed element is overflowing its bounds,
// either vertically or horizontally.
// Will temporarily modify the "overflow" style to detect this
// if necessary.
function checkOverflow(el)
{
var curOverflow = el.style.overflow;
if ( !curOverflow || curOverflow === "visible" )
el.style.overflow = "hidden";
var isOverflowing = el.clientWidth < el.scrollWidth
|| el.clientHeight < el.scrollHeight;
el.style.overflow = curOverflow;
return isOverflowing;
}
Now, in a loop remove text and check until it is not overflowing anymore. Append an ellipsis character (String.fromCharCode(8230)) to the end, but only if it was overflowing.
To avoid any flickering effects during that operation, you can try working on a hidden copy of the element, but I'm not sure if the browsers do the necessary layout calculations on an element that's not visible. (Can anyone clarify that?)

Related

change start position of horizontal scrollbar without jquery

In Jquery I'm aware you can move the scrollbars' starting location. Is this possible with pure javascript? To clarify, when the user loads the page I simply want the horizontal scrollbar to start scrolled all the way to the right, instead of starting at the left. If there are cross-browser issues, I'm particularly concerned with this working in Chrome.
document.body.scrollLeft = ( divRef.scrollWidth - divRef.offsetWidth ) / 2 ;
NOTE:
This can give odd results with IE8 and earlier.
I've made an example with a div, you can easily adjust this to your body tag, or another div, please see the demo.
var a = document.getElementById('body');
console.log(a.clientWidth)
function moveWin(a) {
window.scrollTo(a.clientWidth,0);
}
moveWin(a)
DEMO
SIDENOTE:
To select the body, simply use
var a = document.getElementsByTagName('body')[0]

Get height at which scroll bars will appear in javascript

Here's a couple of ways to ask this question:
How can I get the height (in pixels) at which the page will start having scroll bars? In other words, how do i get the window height at which a scroll bar will appear?
How can I get the maximum height of all elements on the page that don't have relative
heights (e.g. height: 100%)?
This question is related, but the answer doesn't do what I want in the case of relative heights: Finding the full height of the content of a page/document that can have absolutely positioned elements
I made a js fiddle of what I'm talking about: http://tinyurl.com/kgf8dae . Unfortunately, jsfiddle seems to break the relative height put on div e - run it as an html page in a normal browser to see the real behavior.
I might be misunderstand the question. In general, if the window height is less than the document height you will get a vertical scrollbar.
So in jQuery the check might look like this:
if( $(document).height() > $(window).height() ){ /* There will be a scrollbar */ }
You can perform this check within DOM changing and window resizing events to ascertain if a scrollbar has appeared. To preemptively determine if an event would cause a scrollbar to appear can be tricky and would likely require some understanding of the page and potential events to handle efficiently.
This is tagged through jQuery so I'm going to use jQuery; even though it's not mentioned in the question body.
a) It sounds like you want to get the height of the viewport (window); which can be retrieved like this:
var height = $(window).height();
If the height of the document (page) exceeds the height of the window, and there are no CSS properties blocking the display of scrollbars, then scrollbars will indeed by visible.
if( $(document).height() > $(window).height() )
b) This is going to be a bit trickier, in the sense the only way off the top of my head is to query every DOM element.. this is not a elegant solution; and in fact I'd ask you to reconsider your approach if you really you must do this. That said.. for curiosity...
If you're looking for the max height, in the sense of the largest element - then this would work:
// Get height of largest element.
var max_height = 0;
$('*').each( function(){
// skip <html> and <body>
if( ( $(this).get(0) == $('body').get(0) ) || ( $(this).get(0) == $('html').get(0) ) )
return;
var current_height = $(this).height();
if( current_height > max_height )
max_height = current_height;
});
For example, running that on this page...
> console.log( max_height );
570
However, I'm not sure if you want the maximum height of all combined elements.. In which case we obviously need to add all the elements up, but there's the obvious problem: elements are nested!
If this is what you want, then by using .children() we can just iterate through the lengths of the elements that are immediate children of your containing element/body.
// Get height of all combined elements
var combined_height = 0;
$('body').each( function(){ // replace with containing element?
combined_height = combined_height + jQuery(this).height();
});
For example, running that on this page:
> console.log(combined_height);
2176
Using the HTML/CSS from the example your provided via (jsfiddle.net/RMe3n/1). The answer is and always will be 242.
However, I assume you're looking for a more dynamic approach. Running the following after DOM ready will also produce 242:
var answer = 0;
$('#absolutes > div').each(function(){
var h = $(this).outerHeight(true);
if(answer < h) answer = h;
})
alert(answer);
While the above will solve for the particular HTML/CSS you provided it makes a lot of assumptions about the page's HTML structure and CSS.
Is it possible that the problem you are attempting to address with JS could be resolved in a "cleaner" way by adjusting the HTML/CSS of your page?
If you are looking for a fool proof JS method to account for ALL the multitude of unique layouts/styles that exist now and may exist as more CSS3 display types are adopted in the future I believe you're out of luck. There is no recommendable, consistent, efficient way to do so.
Note: If this is more than just a theoretical discussion, consider being more specific about the exact scenario you are faced with as there is likely a vastly different approach that may resolve the issue.

Javascript/jQuery get true width and position of float affected element?

Is it possible to get the width (using javascript or jQuery) of a float-affected element? When text is being pushed over due to a floating image is it possible to get its position and true width? I have attached an image to explain better.
Code example,
<div>
<img style="...float: left"/>
<h1>A title!</h1>
<p>Text!</p>
<h1>New header added.</h1>
</div>
Picture
I need to find the width starting from the arrow, (the gray box is the image)(the dotted line is the width according to Firefox inspect mode).
I would like to avoid changing all the elements display types if possible.
Thank you!
I'm a little late to the party, but I had a similar problem and came up with a solution which (so far) seems to work in all instances of this issue. I like this solution because as far as I can tell, it works independent of the floating element - all you need is the element whose true width/position you want to get, nothing more. I've done it in pure Javascript for speed purposes, but it can easily be streamlined with jQuery and a separate CSS Stylesheet if you so choose.
//Get the rendered bounding box for the content of any HTMLElement "el"
var getLimits = function(el) {
//Set a universal style for both tester spans; use "!important" to make sure other styles don't mess things up!
var testerStyle = 'width: 0px!important; overflow: hidden!important; color: transparent!important;';
//Create a 'tester' span and place it BEFORE the content
var testerStart = document.createElement('SPAN');
testerStart.innerHTML = '|';
var testerFloat = ' float: left!important;';
testerStart.setAttribute('style', testerStyle + testerFloat);
//Insert testerStart before the first child of our element
if (el.firstChild) {
el.insertBefore(testerStart, el.firstChild);
} else {
el.appendChild(testerStart);
}
//Create a 'tester' span and place it AFTER the content
var testerEnd = document.createElement('SPAN');
testerEnd.innerHTML = '|';
testerFloat = ' float: right!important;';
testerEnd.setAttribute('style', testerStyle + testerFloat);
el.appendChild(testerEnd);
//Measure the testers
var limits = {
top: testerStart.offsetTop,
bottom: testerEnd.offsetTop + testerEnd.offsetHeight,
left: testerStart.offsetLeft,
right: testerEnd.offsetLeft
}
//Remove the testers and return
el.removeChild(testerStart);
el.removeChild(testerEnd);
return limits;
};
So, in your case, the code would just be:
var paragraphBoundingBox = getLimits($('div>p').get(0));
A couple things to note:
1) The float direction would be reversed if you are using an RTL language
2) All of the four edge positions in the output object are relative to the el.offsetParent - use this handy function can find their positions relative to the document.
First of all, the "full width" is exactly the true width.
You can watch this picture, it can help you understand why the true width and true position of the affected element is the way firefox tells you.
http://i.stack.imgur.com/mB5Ds.png
To get the width of inline text where it's pushed right by the float image, there's no good way except using the full width minus the float image's width.
var w = $('p').width()
- $('img').width()
- $('img').css('margin-left').replace("px", "")
- $('img').css('margin-right').replace("px", "")
- $('img').css('padding-left').replace("px", "")
- $('img').css('padding-right').replace("px", "")
- $('img').css('border-left-width').replace("px", "")
- $('img').css('border-right-width').replace("px", "");

Indent code on a web page like in a code editor?

Is it possible to wrap indented code on a web page the way it's done in a code editor? See the screenshot comparison below to better understand what I mean:
pre-wrap on a web page:
Wrapping of indented lines in a code editor:
What I am implying is that the indented lines maintain indentation even after wrapping. This doesn't seem to happen on web pages. Is there a CSS property that does this? (JavaScript would be fine too.)
NOTE: I am not talking about code highlighting here. It's about indentation of wrapped lines.
If this matters — this is how I am showing code blocks on my web pages:
<pre><code>if ( is_page() && $post->post_parent ) {
return $post->post_parent;
} else {
return false;
}
</code></pre>
...and the white-space: pre-wrap; style is applied on pre tag.
Algorithm
Get the contents of the element, and generate a list of all lines.
Use the element to measure the width of a space character.
Create a document fragment (for optimal performance!).
Loop through all lines. For each line:
Count the number of preceeding white space.
Create a block-level element (such as <div>).
Set the marginLeft (or paddingLeft, if you wish) property to the product of the size of a single space and the number of prefixed spaces.
Append The contents of the line (left trimmed).
Replace the contents of the actual element with the fragment.
Code (demo: http://jsfiddle.net/YPnhX/):
/**
* Auto-indent overflowing lines
 * #author Rob W http://stackoverflow.com/u/938089
* #param code_elem HTMLCodeElement (or any element containing *plain text*)
*/
function autoindent(code_elem) {
// Grab the lines
var textContent = document.textContent === null ? 'textContent' : 'innerText';
var lines = code_elem[textContent].split(/\r?\n/),
fragment = document.createDocumentFragment(),
dummy, space_width, i, prefix_len, line_elem;
// Calculate the width of white space
// Assume that inline element inherit styles from parent (<code>)
dummy = document.createElement('span');
code_elem.appendChild(dummy);
// offsetWidth includes padding and border, explicitly override the style:
dummy.style.cssText = 'border:0;padding:0;';
dummy[textContent] = ' ';
space_width = dummy.offsetWidth;
// Wipe contents
code_elem.innerHTML = '';
for (i=0; i<lines.length; i++) {
// NOTE: All preceeding white space (including tabs is included)
prefix_len = /^\s*/.exec(lines[i])[0].length;
line_elem = fragment.appendChild(document.createElement('div'));
line_elem.style.marginLeft = space_width * prefix_len + 'px';
line_elem[textContent] = lines[i].substring(prefix_len);
}
// Finally, append (all elements inside) the fragment:
code_elem.appendChild(fragment);
}
Browser compatibility
IE8 + (IE7- doesn't support white-space:pre-wrap)
Chrome 1+
Firefox 3+
Safari 3+
Opera 9+ (previous versions untested)
Notes
In this example, I calculated the width of a space (U+0020) character. The similar method is used if you want to calculate different values for other white-space characters.
Follow-up to the previous note: To account for tabs, you have to take a hard route, which degrades performance. For each line, set the contents of the dummy (appended to code_elem!) to the prefixed white space, then calculate the width using .offsetWidth.
Each time, the element is rendered. For hundreds of lines, this method may cause a spike in the CPU usage. Don't ever use tabs to display code in a web page!
The autoindent function assumes that the contents of a element is plain text.

Jquery - Truncate Text by Line (not by character count)

I need a Jquery script to truncate a text paragraph by line (not by character count).
I would like to achieve an evenly truncated text-block. It should have a "more" and "less" link to expand and shorten the text paragraph. My text paragraph is wrapped in a div with a class, like this:
<div class="content">
<h2>Headline</h2>
<p>The paragraph Text here</p>
</div>
The closest solution i could find on SOF is the one below (but it`s for textarea element and does not work for me):
Limiting number of lines in textarea
Many thanks for any tips.
Ben
For a basic approach, you could take a look at the line-height CSS property and use that in your calculations. Bear in mind that this approach will not account for other inline elements that are larger than that height (e.g. images).
If you want something a bit more advanced, you can get the information about each line using getClientRects() function. This function returns a collection of TextRectangle objects with width, height and offset for each one.
See this answer here for an example (albeit an unrelated goal) of how getClientRects() works.
Update, had a bit of time to come back and update this answer with an actual example. It's basic, but you get the idea:
http://jsbin.com/ukaqu3/2
A couple of pointers:
The collection returned by getClientRects is static, it won't update automatically if the containing element's dimensions change. My example works around this by capturing the window's resize event.
For some strange standards-compliance reason that I'm not understanding, the element you call getClientRects on must be an inline element. In the example I have, I use a container div with the text in another div inside with display: inline.
I made this little jQuery code to allow me truncate text blocks by line (via CSS classes), feel free to use and comment it.
Here is the jsFiddle, which also include truncate functions by char count or word count. You can see that currently, resize the window won't refresh the block display, I'm working on it.
/*
* Truncate a text bloc after x lines
* <p class="t_truncate_l_2">Lorem ipsum magna eiusmod sit labore.</p>
*/
$("*").filter(function () {
return /t_truncate_l_/.test($(this).attr('class'));
}).each(function() {
var el = $(this);
var content = el.text();
var classList = el.attr('class').split(/\s+/);
$.each(classList, function(index, item){
if(/^t_truncate_l_/.test(item)) {
var n = item.substr(13);
var lineHeight = parseInt(el.css('line-height'));
if(lineHeight == 1 || el.css('line-height') == 'normal')
lineHeight = parseInt(el.css('font-size')) * 1.3;
var maxHeight = n * lineHeight;
var truncated = $.trim(content);
var old;
if(el.height() > maxHeight)
truncated += '...';
while(el.height() > maxHeight && old != truncated) {
old = truncated;
truncated = truncated.replace(/\s[^\s]*\.\.\.$/, '...');
el.text(truncated);
}
}
});
});
why not make the p element with overflow: hidden; give fixed line height, caluclate the height of the div so id contains exactly the number of lines you require and the only change the height of the p from javascript.
p{
overflow:hidden;
line-height:13px;
height:26px; /* show only 2 rows */
}
<script type="text/javascript">
function seeMoreRows(){
$(p).height("52px");
}
</script>
I made a small module that works with pure text content, no nested tags and no css-padding on the text-containing element is allowed (but this functionality could easily be added).
The HTML:
<p class="ellipsis" data-ellipsis-max-line-count="3">
Put some multiline text here
</p>
The Javascript/Jquery:
( function() {
$(document).ready(function(){
store_contents();
lazy_update(1000);
});
// Lazy update saves performance for other tasks...
var lazy_update = function(delay) {
window.lazy_update_timeout = setTimeout(function(){
update_ellipsis();
$(window).one('resize', function() {
lazy_update(delay);
});
}, delay);
}
var store_contents = function(){
$('.ellipsis').each(function(){
var p = $(this);
p.data('ellipsis-storage', p.html());
});
}
var update_ellipsis = function(){
$('.ellipsis').each(function(){
var p = $(this);
var max_line_count = p.data('ellipsis-max-line-count');
var line_height = p.html('&nbsp').outerHeight();
var max_height = max_line_count*line_height;
p.html(p.data('ellipsis-storage'));
var p_height = p.outerHeight();
while(p_height > max_height){
var content_arr = p.html().split(' ');
content_arr.pop();
content_arr.pop();
content_arr.push('...');
p.html(content_arr.join(' '));
p_height = p.outerHeight();
}
});
}
} )();
I hope you like it!
If you used a monospaced font, you'd have a shot at this working, as you'd have a good idea how many letters fit onto each line, for an element of a defined width. However, if a word breaks across lines, then this might get tricky..
e: found another question which is basically what you're after - they didn't really have a resolution either, but to my mind, the line-height and element height seems closest.
"How can I count text lines inside a dom element"
tl;dr - set a height on your container div and then use the jQuery dotdotdot plugin
Was about to make #Andy E's awesome example into a plugin, but then realized https://github.com/BeSite/jQuery.dotdotdot could pull this off. Our use case is we want to show one line on desktop widths and two lines on mobile/tablet.
Our CSS will just set the container div to the equivalent of one or two line-height's accordingly and then the dotdotdot plugin appears to handle the rest.

Categories

Resources