josephschmitt / clamp.js Goto Github PK
View Code? Open in Web Editor NEWClamps an HTML element by adding ellipsis to it if the content inside is too long.
Home Page: http://joe.sh/clamp-js
Clamps an HTML element by adding ellipsis to it if the content inside is too long.
Home Page: http://joe.sh/clamp-js
Tried to clamp tags but doesn't work. Can any modification be done to accommodate this?
Uncaught SyntaxError: Unexpected token (
at line 8.
To reproduce: create an HTML file along these lines:
<!DOCTYPE html>
<html>
<head>
<script src="clamp.min.js"></script>
</head>
<body>
Test
</body>
</html>
Run it in in a local webserver in Chrome and observe the error in the JS console.
I'd like an option to stop after a full word, actually, instead of moving on to the last step (individual characters.) So you could set, say, boundariesOnly : true
, and then once it got to the step where it's found a space but it's a little too short, it would STOP and put an ellipsis there. Because I'd rather only have full words, sometimes, even if that means my last line is shorter than the full width of my element.
When a sentence ending with a dot creates ellipsis, even when de sentence is just 1 word.
This is not happening in Chrome. Only in Firefox and IE.
How can I solve this?
Using clamp for displaying list of emails (chrome). Email format is a standard outlook format
Smith, John (EY123987) <john[email protected]>; Simpson, Homer (EY123987) <homer[email protected]>...
Clamp replace < with <, and browser understands it as a HTML element, thus loosing text <[email protected]>
Issue is on this line
element.innerHTML = target.nodeValue + ' ' + truncationHTMLContainer.innerHTML + opt.truncationChar;
I have applied a fix on local copy of clamp.js file
element.innerHTML = escapeHtml(target.nodeValue) + ' ' + truncationHTMLContainer.innerHTML + opt.truncationChar;
Where escapeHtml is
function escapeHtml(unsafe) {
return unsafe
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
Please fix it in a main version
http://jsfiddle.net/d3o2w1uu/40/
With anchor tag inside p tag, clamp.js works perfectly fine. But, if we remove the anchor tag clamp.js fails.
Hey guys,
First of all, this is a great job ! Thank you !
I just ran over some problem using clamp with react. The problem is that I can't pass "window" to the function and in that environment, it doesn't know what it is.
An easy fix would just be to pass window as an option :
in Clamp.js :
var self = this,
win = options.window || window,
// ...
I've made a pull request : #62
Thanks guys !
Let's say you have a div that contains enough text that when rendered in the browser yields 4 lines of text. Let's also say that you set up clamp.js as follows:
$clamp(el, {clamp: 4, useNativeClamp: false});
The last character in your text will end up getting clamped. We are using version 0.4.
Suggested fix:
Remove from line 234 the "=" in your <= comparator so that it looks like:
if (height < element.clientHeight) {
This solved the issue.
My code:
var module = $('.eventon_desc_in > p:first-child');
for (var i = module.length - 1; i >= 0; i--) {
$clamp(module[i], {clamp: 2});
}
Works like a charm in Chrome, nothing happens in Firefox however.
Although it hasn't been updated in 6 years, It did solved my problem
I have a table, and inside each rows there's a single <td> element with the class "clampThis" that I'd like to clamp the text within.
So I thought something like this would work
var item = $('.clampThis');
$clamp(item, {clamp: 1, useNativeClamp: false});
But I get this error instead:
Uncaught TypeError: Cannot read property 'webkitLineClamp' of undefined clamp.min.js:11
Maybe I'm doing it the wrong way? I'm not sure. I'm not a great JavaScript wizard, so help would be much appreciated. :)
This happens on Google Chrome (Version 31.0.1650.63 m) on Windows 7.
function getLastChild(elem) {
if (elem.lastChild.children && elem.lastChild.children.length > 0) {
return getLastChild(Array.prototype.slice.call(elem.children).pop());
} else if (!elem.lastChild || !elem.lastChild.nodeValue || elem.lastChild.nodeValue == '' || elem.lastChild.nodeValue == opt.truncationChar) {
elem.lastChild.parentNode.removeChild(elem.lastChild);
return getLastChild(element);
} else {
return elem.lastChild;
}
}
Hello,
i like this plugin but now i have a first conflict that i can not solved :(
I use jq owlCarousel and on this section have clamp.js problems :(
<div class="thisCarousel">
<div class="aucSlidItem">
<div style="background-image: url('<?php echo IMG_URI; ?>dummy/01.jpg');"></div>
<div class="clamp"><a id="auc_1" data-mode="win" href="<?php link::get('auction/view?id=%s', ['test_auktion_1']); ?>" onclick="contentWindow( $(this) ); return false;">1Erster Versuch - stilvolles Date langer name</a></div>
<div>Deutschland<span>xxxx</span></div>
<div class="auCtn cal" data-end="11/11/2017 16:00:00"></div>
<div><?php wwmCalc::getAucPrice(999, 'EUR', '["2017-12-18 20:00:00",5.55]'); ?></div>
</div>
<div class="aucSlidItem">
<div style="background-image: url('<?php echo IMG_URI; ?>dummy/01.jpg');"></div>
<div class="clamps"><a id="auc_2" data-mode="win" href="<?php link::get('auction/view?id=%s', ['test_auktion_2']); ?>" onclick="contentWindow( $(this) ); return false;">2Erster Versuch - stilvolles Date2</a></div>
<div>Deutschland<span>xxxx</span></div>
<div class="auCtn cal" data-end="11/11/2017 16:00:00"></div>
<div><?php wwmCalc::getAucPrice(999, 'EUR', '["2017-12-18 20:00:00",5.55]'); ?></div>
</div>
<!-- more items.... -->
</div>
<script type="text/javascript">
$('.thisCarousel').owlCarousel({
loop: false,
margin: 20,
nav: false,
dots: false,
autoplay: true,
autoplayTimeout: 2500,
lazyLoad: true,
responsiveClass: true,
responsive: {
0: { items: 2 },
700: { items: 3 },
1200: { items: 4 }
}
});
setTimeout(function(){
var items = document.getElementsByClassName('clamp');
for( i in items ){
if( items.hasOwnProperty(i) ){
$clamp(items[i], {clamp: (( items[i].hasAttribute("data-clamp") ) ? items[i].getAttribute("data-clamp") : 'auto')});
}
}
}, 1500);
// result TypeError: a.lastChild is null on getLastchild() #121
<script>
This error is only on browsers without webkitLineClamp
I hope any can help me to fix :(
"truncate" function works incorrect in case of one-letter-string.
It finds no valid chuncks (line 198) and finally falls with "elem.lastChild is null" error in "getLastChild".
In responsive design. When invoking clamp, it does not use the original text. This only works for a single load or invocation. Once clamp occurs, game over. No original text is stored.
Adding clamp to the window resize event, shrink screen down, then enlarge will remain truncated down to the smallest resize point.
I've added a data attribute for original in the past as a solution. This could probably be added in this plugin.
Example:
<div class="rc-description">In sit amet dictum velit. Vivamus quam mi, com…</div>
<div class="rc-description" data-original="In sit amet dictum velit. Vivamus quam mi, com In sit amet dictum velit. Vivamus quam mi, com In sit amet dictum velit. Vivamus quam mi, com In sit amet dictum velit. Vivamus quam mi, com">In sit amet dictum velit. Vivamus quam mi, com…</div>
Needs to use the original pre-truncated text, not the already truncated text.
If you attempt to put in a word that is too long for the container, it wraps the text but crops off the end of the word. This really should hyphenate the word that is too long and wrap it onto the next line before continuing with the string. Example is here: http://jsfiddle.net/ebqtundo/
This word should read Supercalifragalisticexpialdocius
but has been cropped.
getLastChild looks odd, you should check if elem.lastChild exists before use it:
if (elem.lastChild.children && elem.lastChild.children.length > 0) {
Another conditional has if (!elem.lastChild and then tries to use elem.lastChild
else if (!elem.lastChild || !elem.lastChild.nodeValue || elem.lastChild.nodeValue == '' || elem.lastChild.nodeValue == opt.truncationChar) {
elem.lastChild.parentNode.removeChild(elem.lastChild);
My usage example:
$clamp(this, {
clamp: 'auto',
useNativeClamp: false,
truncationHTML: '<a href="#">read more</a>'
});
I'd like to use this js code as a Rails asset using https://rails-assets.org/, but there is no version defined in this repo and it can't be turned into a gem. Could you please add version?
Ill probably submit a merge request in my freetime; however, as it stands, functions are extremely large and complex and there is little encapsulation of features/functions even though the whole thing is defined in a closure.
The clamp function is HUGE. it creates utility subfunctions which should be defined externally to the function (its generally bad practice unless its a callback to a utility that you're using. like _.each )
there are missing semicolons, as well as the usage of global variables (why so afraid to use this?)
Infact self isnt used...
On that note.... use JSLint/JsHint its how I found a lot of these coding style challenges for such a useful library.
Title says it all.
Uncaught TypeError: Cannot read property 'webkitLineClamp' of undefined
at clamp (clamp.js:32)
Subj
$clamp(node, {clamp:2});
chrome : Displays two lines normally
Edge browser : only According to a line
Hi. A good idea is to add callback support for clamping with success, no clamp needed.
Current I have the clamped text change color on hover, but the ellipsis remains the same. Is it possible to have it change as well?
div id="clamp">
qwewqeqweqweqweqweqweqwe
qwewqeqweqweqweqweqweqwe
qwewqeqweqweqweqweqweqwe
qwewqeqweqweqweqweqweqwe
qwewqeqweqweqweqweqweqwe
$clamp(document.getElementById("clamp"), {clamp: 3});it doesn't work in chrome.
and there is sth wrong in firefox.
Any thoughts on how one would test usage of clamp in a unit test? I don't see any here.
When using clamp on a span within Chrome (and possibly other browsers) and using the "contenteditable" attribute on the span to allow inline editing, after clearing the text, the area then becomes uneditable. It still shows the editable border and everything, but no characters you type ever appear in the field. When I stop using clamp, normal functioning returns.
This seems to bring two problems to light. One is that I have not been able to find a way to easily suspend the use of clamp on a field. The second is the bug.. Editing does still appear to function, until you remove the last character from the field.
<h1></h1>
Trying to clamp the above element fails hard in Firefox on line 109:
if (elem.lastChild.children && elem.lastChild.children.length > 0)
with:
TypeError: elem.lastChild is null
Trying to fix function getLastChild()
just propagates the error elsewhere, so I won't go digging around too deep.
Usage:
$clamp(contentElement, {
clamp: numLines,
useNativeClamp: false,
truncationChar: ' ',
truncationHTML: '... see more'
});
original text: jpaa jpaa jpaa jpaa jpaa jpaa jpaa jpaa jpaa jpaa jpaa jpaa jpaa jpaa jpaa jpaa jpaa jpaa
Clamped text: jpaajpaajpaajpaajpaajpaajpaajpaa jpaa jpaa jpaa jpaa jpaa jpaa jpaa jpaa jpaa jpaa ... see more
truncationChar works fine with these uses:
truncationChar: ' '
truncationChar: ''
If it's not worth fixing, maybe just add a note to the ReadMe.
The method getLineHeight
uses parseInt
, which always rounds decimal numbers down. Chrome returns a decimal when calling computeStyle
, which can (in some cases) be something like 23.994
. So in this case Chrome will calculate the value to be 23
, but FF and IE round it up to 24
. This small difference though can mean the difference between lines failing to truncate to the correct number of lines. I propose something like this Math.round(parseFloat(lh))
instead of parseInt(lh)
to give consistent results across browsers.
Tested on Chrome 53.0.2785.116 m (64-bit), FireFox 48.0.2, Microsoft Edge 38.14393.0.0.
Please state what license this code is released under. I'm not allowed to use anything in my current project that doesn't have a sufficiently permissive license explicitly stated.
http://opensource.org/licenses
The MIT license is a common option, but whatever you pick please clearly state it in the readme file or add a new file to the project called LICENSE
containing the text of the license in it.
Under current copyright law, if no license is stated, it is copyrighted.
Thanks :)
Haven't played with it yet so I'm not sure how it behaves relative to clamp in Webkit, but might be worth a try.
i have been searching for auto clamping according to the height for a long time now.
but not sure what needs to be done for this. can you give an example of fitting to several sizes?
thanks!
Example of the issue:
If you have text that fits into two lines and you are clamping to 2 lines, truncation/clamping is unnecessary. However, with the current version you'll lose the last letter of the text and it will be replaced by the ellipsis.
So you might expect:
clamp.js is a fun way
to clamp text
But you get
clamp.js is a fun way
to clamp tex...
This issue seems to be caused by line 221, which calls the initial truncate even when the height matches the max height.
if (height <= element.clientHeight) {
Changing this to a simple '<' seems to fix the problem.
<h4>
use clampJS:
</h4>
<p id="ellipsis" style="width:100px;">
11111111111111111111111111111222222222222222211111111111111111111111111112222222222222222111111111111111111111111111122222222222222222
</p>
<script src="Clamp.js-master/Clamp.js-master/clamp.min.js"></script>
<script>
$clamp( document.getElementById("ellipsis"), {clamp: 2});
</script>
There is no way to remove clamp styling from a
tag. Like in case of read more functionality, I want to remove the clamp (truncationHTML option is not fulfilling my requirement).
document.getElementsByTagName('body')[0].getElementsByTagName('div')[0].getElementsByTagName('p')[0]
this would pick the p tag content, currently nothing is being clamped
I've been testing Clamp.js with the following simple code. I get Firefox consistently showing one less line, while Chrome and IE perform ok.
<html>
<head>
<meta http-equiv=Content-Type content="text/html; charset=utf-8" />
<style>
.mypar {
margin:0; border:0; padding:0; }
.mydiv1 {
position:fixed; background:yellow;
top:50px; left:50px;
margin:0; border:1px solid; padding:0;
width:205px; height:92px; line-height:120%;
font-family:Arial; font-size:12px; color:black; }
.mydiv2 {
position:fixed; background:yellow;
top:200px; left:50px;
margin:0; border:1px solid; padding:0;
width:205px; height:92px; line-height:120%;
font-family:Arial; font-size:12px; color:black; }
</style>
</head>
<body>
<script>
window.onload=function() {
var p = document.getElementById("p1");
$clamp(p, {clamp: 4}); }
</script>
<div class="mydiv1">
<p id="p1" class="mypar">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
</div>
<div class="mydiv2">
<p id="p2" class="mypar">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
</div>
</body>
</html>
I'm trying to clamp data inside anchor tag which in turn inside header, but it was not working as expected
I'm i doing the right way ?
HTML
<h1><a id="mylink" href="#"> Curabitur magna lectus, cursus at euismod sed, aliquet a lectus. Vivamus ac magna purus, in eleifend eros.</a></h1>
JS
var header = document.getElementById('mylink');
$clamp(header, {clamp: 2, useNativeClamp: false});
Can the tags be added for each release for git auto-update on cdnjs?
not good in firefox.
Can clamp.js be toggle to display the rest of the content?
This project seems like it might be dead, but I thought I'd request a feature.
I'm currently using clamp.js (love it by the way) in a site with responsive design, and I want to clamp some text when the layout changes (i.e. when someone switches from portrait to landscape on iPad, or vice versa). I've accomplished this without a problem.
When someone changes the layout back, however, I want to unclamp their text, but it's actually been deleted. Would be great if clamp could keep track of the original text (in an html data attribute?) so it could be restored or re-clamped at a higher # of lines.
Something as simple as adding a span within the clamped element, makes it completely removed when in the non-webkit-css mode.
Perhaps the webkit css mode should be removed as then this case would not accidentally make sites unusable in most browsers?
See for example:
http://codepen.io/anon/pen/kkoZBx
where the only way to see something under "Clamp.js way" is in Chrome/Chromium, Webkit browsers.
We at VersionEye are working hard to keep up the quality of the bower's registry.
We just finished our initial analysis of the quality of the Bower.io registry:
7530 - registered packages, 224 of them doesnt exists anymore;
We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).
Sadly, your library josephschmitt/Clamp.js
is one of them.
Can you spare 15 minutes to help us to make Bower better?
Just add a new file bower.json
and change attributes.
{
"name": "josephschmitt/Clamp.js",
"version": "1.0.0",
"main": "path/to/main.css",
"description": "please add it",
"license": "Eclipse",
"ignore": [
".jshintrc",
"**/*.txt"
],
"dependencies": {
"<dependency_name>": "<semantic_version>",
"<dependency_name>": "<Local_folder>",
"<dependency_name>": "<package>"
},
"devDependencies": {
"<test-framework-name>": "<version>"
}
}
Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.
NB! Please validate your bower.json with jsonlint before commiting your updates.
Thank you!
Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!
Consider the following screenshot:
https://www.dropbox.com/s/2y1vnoaq2p7i0m9/_Screenshot%202014-06-03%2014.48.57.png
The third word (partly elliptisized in the second text line on the screenshot) is "ID". The ellipsis is clearly unnecessary here.
The following little change seems to solve the problem: pdkovacs@2756c06 . This solution is, however, completely based on "informal reasoning", that is, without me really understanding the details of the implementation. (I just told to myself as I was debugging the issue: "Hey, why do we need to do anything if the clientHeight equals the required height?")
Any comments? Any advices on what I may be missing in terms of configuration, usage scenario, etc?
I have an element with a fixed height and Clamp.js is deleting its content if there is a span within. There were some spans from beginning to the end of the element. Clamp.js was called like this:
$('.clamp').each(function() { $clamp(this, { clamp: 'auto' }) });
The spans were:
<span style="font-style: italic;">...</span>
Don't know by what this is caused, removed Clamp.js for now.
Matthias
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.