Skip to content

Commit 13e0d5a

Browse files
committed
Use more smarts to determine where "less"/"more" goes, so e.g. a <p> followed by a <table> is treated right.
1 parent 669d3a7 commit 13e0d5a

File tree

2 files changed

+31
-16
lines changed

2 files changed

+31
-16
lines changed

example.html

+7-5
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,11 @@
1010
$('.example').truncate({max_length: 24});
1111
});
1212

13-
</script>
13+
</script>
14+
<style type="text/css">
15+
table { border-collapse: collapse; }
16+
td, th { border: 1px solid #000; }
17+
</style>
1418
</head>
1519
<body>
1620

@@ -45,11 +49,9 @@ <h2>Example 4: Handling tables</h2>
4549
<p>Hello!</p>
4650

4751
<table>
48-
<tr><th>Name</th></tr>
49-
<tr><td>Lauren Ipsum</td></tr>
52+
<tr><th>Foo</th><th>Bar</th></tr>
53+
<tr><td>Lauren</td><td>Ipsum</td></tr>
5054
</table>
51-
52-
<p>Goodbye!</p>
5355
</div>
5456

5557
</body>

jquery.truncator.js

+24-11
Original file line numberDiff line numberDiff line change
@@ -16,20 +16,15 @@
1616
if (content_length <= opts.max_length)
1717
return; // bail early if not overlong
1818

19-
var actual_max_length = opts.max_length - opts.more.length - 3; // 3 for " ()"
19+
var actual_max_length = opts.max_length - opts.more.length - 3; // 3 for " ()"
2020
var truncated_node = recursivelyTruncate(this, actual_max_length);
21-
var full_node = $(this);
21+
var full_node = $(this).hide();
2222

2323
truncated_node.insertAfter(full_node);
24-
// This is an ugly approximation for getting the last block tag:
25-
// we just pick the last <p> or else the container itself.
26-
truncated_node.find('p:last').add(truncated_node).eq(0).
27-
append(' (<a href="#show more content">'+opts.more+'</a>)');
28-
29-
full_node.hide();
30-
full_node.find('p:last').add(full_node).eq(0).
31-
append(' (<a href="#show less content">'+opts.less+'</a>)');
32-
24+
25+
findNodeForMore(truncated_node).append(' (<a href="#show more content">'+opts.more+'</a>)');
26+
findNodeForLess(full_node).append(' (<a href="#show less content">'+opts.less+'</a>)');
27+
3328
truncated_node.find('a:last').click(function() {
3429
truncated_node.hide(); full_node.show(); return false;
3530
});
@@ -81,5 +76,23 @@
8176
function squeeze(string) {
8277
return string.replace(/\s+/g, ' ');
8378
}
79+
80+
// Finds the last, innermost block-level element
81+
function findNodeForMore(node) {
82+
var $node = $(node);
83+
var last_child = $node.children(":last");
84+
if (!last_child) return node;
85+
var display = last_child.css('display');
86+
if (!display || display=='inline') return $node;
87+
return findNodeForMore(last_child);
88+
};
89+
90+
// Finds the last child if it's a p; otherwise the parent
91+
function findNodeForLess(node) {
92+
var $node = $(node);
93+
var last_child = $node.children(":last");
94+
if (last_child && last_child.is('p')) return last_child;
95+
return node;
96+
};
8497

8598
})(jQuery);

0 commit comments

Comments
 (0)