Read more-less in ol tag

Viewed 67

I was making read more-less toggle with jquery, which would appear after 100th symbol in text.

Right now i have code that does that with 100th symbol in html of OL tag. It works just like i want, but 100th symbol in markup is not the same as in text, because it counts tags too.

var showChar = 100;
var ellipsestext = "...";
var moretext = "Ещё";
var lesstext = "Скрыть";

$('.more').each(function () {
    var content = $(this).html();
    if (content.length > showChar) {
        var c = content.substr(0, showChar);
        var h = content.substr(showChar, content.length - showChar);
        var position = h.indexOf('</li>');
        var h = [h.slice(0, position), '</span></li><span class="morecontent">', h.slice(position + 5)].join('');
        var html = c + '<span class="moreellipses">' + ellipsestext + '</span><span class="morecontent"><span>'
            + h + '</span><a href="" class="morelink">' + moretext + '</a></span>';
        $(this).html(html);
    }
});

$(".morelink").click(function () {
    if ($(this).hasClass("less")) {
        $(this).removeClass("less");
        $(this).html(moretext);
        $('.morecontent').each(function() {
            $(this).css('display', 'none');
        });
        $('.moreellipses').css('display', 'inline');
    } else {
        $(this).addClass("less");
        $(this).html(lesstext);
        $('.morecontent').each(function () {
            $(this).css('display', 'inline');
        });
        $('.moreellipses').css('display', 'none');
    }
    return false;
});

I tried to determine the position of 100th symbol in text in html, by getting substring from text, but substring might appear sooner in html, or even be broken by tags. Is there a way to modify my code, so that 'ellipsestext' would appear after 100th symbol in text?

1 Answers

You should be using also $(this).text() to keep track of the remaining 'available' characters and on each iteration, you should update that value. Then to know in which position you are going to insert your markup you can go searching the indexOf the substring that you'll show

Something like:

const maxShowChar = 100;
let showChar = maxShowChar;
const ellipsestext = "...";
const moretext = "Ещё";
const lesstext = "Скрыть";


$('.more').each(function () {
    var textContent= $(this).text();
    var content = $(this).html();
    if (textContent.length > showChar) {
    [...]
    const textC = textContent.substr(0,showChar);
    const c = content.substr(0, content.indexOf(textC));
    [...]
    }else{
    showChar = showChar - textContent.length;
    }
});
Related