Created
January 16, 2019 11:02
-
-
Save bacanu/de17616cc5de0ec6c6d96e54051e0ba2 to your computer and use it in GitHub Desktop.
Truncate to n number of lines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 'use strict'; | |
| var linesElement = 3; //it will truncate at 3 lines. | |
| var truncateElement = document.getElementById('truncateme'); | |
| var truncateText = truncateElement.textContent; | |
| var getLineHeight = function getLineHeight(element) { | |
| var lineHeight = window.getComputedStyle(truncateElement)['line-height']; | |
| if (lineHeight === 'normal') { | |
| // sucky chrome | |
| return 1.16 * parseFloat(window.getComputedStyle(truncateElement)['font-size']); | |
| } else { | |
| return parseFloat(lineHeight); | |
| } | |
| }; | |
| linesElement.addEventListener('change', function () { | |
| truncateElement.innerHTML = truncateText; | |
| var truncateTextParts = truncateText.split(' '); | |
| var lineHeight = getLineHeight(truncateElement); | |
| var lines = parseInt(linesElement.value); | |
| while (lines * lineHeight < truncateElement.clientHeight) { | |
| console.log(truncateTextParts.length, lines * lineHeight, truncateElement.clientHeight); | |
| truncateTextParts.pop(); | |
| truncateElement.innerHTML = truncateTextParts.join(' ') + '...'; | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment