Question

I'm writing some read-more/less functionality for a text, but I came across the next problem.

My steps: 1) getting the content of a text containing div, with multiple paragraphs.

    var content =  $heroContent.html();

2) I make a substring of the part that is always shown, and a second substring of the full text - the part that is always showing, so actually the hidden part. (that hidden part will be possible to show or hide by clicking a button)

c = content.substr(0, 700)
h = content.substr(700, content.length - roundedLimit)

3) I put the second part inside a span with class morecontent, so that I can hide that content and show it.

html = c + "<span class='morecontent'>" + h + "</span>";

4)I add the html variable above again to my div with text, and make the 'morecontent' hide.

Reason for putting the text in a span is that it can be placed inline with the text before where it broke up. If not in span, the text just appears in the line below, which is not wanted.

The problem: the second substring h, can consist of multiple paragraphs. So when a P tag closes inside variable h, the span tag automatically closes also, hence, the class morecontent only applied to the start of the span till the end of the first paragraph inside.

I tried to fix it with putting the text in a DIV, but then the text doesn't appear inline, and that's really an important 'feature'.

If anyone could give me a fix for this problem, that would be great!

Was it helpful?

Solution

Here is a solution that wraps content in a container, and uses a more/less button to expand/contract the container to show the content:

var content = $('.content').wrapInner('<div class="moreless less">');

$('.moreless').after('<div class="showbutton"><span>More</span><span class="hidden">Less</span></div>');

$('.content').on('click', '.showbutton', function() {
   $(this).prev('.moreless').toggleClass('less');
   $(this).find('span').toggleClass('hidden');
});

CSS:

.content {
    line-height: 20px;
}

.less {
    max-height: 100px;
    overflow: hidden;
}

.hidden {
     display: none;   
}

http://jsfiddle.net/rrvtw/

You would need to put some checks in to make sure you aren't adding a more button when the content is smaller than the container.

OTHER TIPS

Another quick way could be to keep a short and long version rather than a first and second part and on click of a button just swap between the two:

var content =  $heroContent.html();
c = content.substr(0, 700)

html = "<div class='short'>" + c + "</div>" + 
       "<div class='all'>" + content + "</div>";

mybutton.toggle() -> $('.short').hide();
                     $('.all').show(); // and viceversa on second click.

How does that sound?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top