Сначала необходимо сохранить полный текст в переменной, никогда не изменять эту переменную, затем сохранить усеченный текст в другой переменной и, наконец, переключаться между ними в значение переменной, чтобы установить текст для целевого элемента.
Вот синпета:
var textHolder = document.querySelector('.demo');
var fullText = textHolder.innerHTML;
var btn = document.querySelector('.btn');
var textStatus = 'full'; // use this to check the status of text and toggle;
function Truancate(textHolder, limit) {
let txt = textHolder.innerHTML;
if (txt.length > limit) {
let newText = txt.substr(0, limit) + ' ...';
textHolder.innerHTML = newText;
textStatus = 'truncated';
}
}
Truancate(textHolder, textHolder.offsetWidth / 10);
function toggleText() {
// here i want to show full text...
// and also -> btn.innerHTML = 'Hide Text' | 'Show Text;
if (textStatus === 'truncated') {
textHolder.innerHTML = fullText;
textStatus = 'full';
} else {
Truancate(textHolder, textHolder.offsetWidth / 10);
}
}
btn.addEventListener('click', toggleText);
<section class="demo" id="demo">
Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long
line of text so that the words don't wrap when they're not supposed to. Multi-line of course!
</section>
<button class="readMore btn">Read More</button>