How to show only "x" characters in a div?

9

Hello, I'm developing a system where I will be publishing, but I would like that, in each publication, it shows "x" characters, and going from that value, it shows a button labeled "Show more", just like Facebook .

If anyone knows how to do this I will be very grateful.

Example:

  

Lorem ipsum dolor sit amet, consectetur adipiscing elit. In thirst pain   nuisance, suscipit quam in, efficitur ante. Praesent feugiat rhoncus   tellus, in rhoncus nisl ... Show more

    
asked by anonymous 01.02.2016 / 00:59

2 answers

5

First and foremost, there are several ways to do this. For example:

  • Showing partial content based on height. You set the height of the element and the "Show More" button or link simply leaves the full height.
  • Use a script to "cut" the text and save the original, which will be displayed again when you click the button or link.
  • Render the hidden original text and visible cut text and simply swap elements by clicking the link.
  • Render the page with the cut texts and load the complete content via Ajax.

Each approach has advantages and disadvantages, having different levels of implementation complexity.

The approach can still vary depending on the content of the publications, that is, if there are HTML tags or some dynamic content.

Assuming you want to avoid new server access, a little more text by increasing the page size is not a problem for you and you really want to limit it by the amount of characters, the second or third option is more reasonable.

Example

Starting from the second approach, I made a very simple script that cuts the% s texts from the start of the page and automatically adds a "Read more" link.

The cut in the text searches with regular expressions to count the number of spaces until you find the nth word

var wordLimit = 50;

$(function() {
  
  //trata o conteúdo na inicialização da página
  $('.show-summary').each(function() {
    var post = $(this);
    var text = post.text();
    //encontra palavra limite
    var re = /[\s]+/gm, results = null, count = 0;
    while ((results = re.exec(text)) !== null && ++count < wordLimit) { }
    //resume o texto e coloca o link
    if (results !== null && count >= wordLimit) {
      var summary = text.substring(0, re.lastIndex - results[0].length);
      post.text(summary + '...');
      post.data('original-text', text);
      post.append('<br/><a href="#" class="read-more">Leia mais</a>');
    }
  });
  
  //ao clicar num link "Leia mais", mostra o conteúdo original
  $('.read-more').on('click', function() {
    var post = $(this).closest('.show-summary');
    var text = post.data('original-text');
    post.text(text);
  });
  
});
.show-summary {
  width: 300px;
  background: #eee;
  margin: 5px;
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="show-summary">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
<div class="show-summary">Sed ut perspiciatis unde omnis iste natus error sit voluptatem</div>
<div class="show-summary">Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</div>
<div class="show-summary">Sed ut perspiciatis unde omnis iste natus error sit</div>
<div class="show-summary">Sed ut perspiciatis unde omnis iste natus error sit voluptatem   accusantium</div>
    
01.02.2016 / 02:32
7

Using CSS

CSS does not have a specific way of counting "x" characters, but there are some things that can help you a bit:

  • overflow:hidden causes content to be cut when it does not fit in a given block

  • text-overflow:ellipsis causes the cut text to be indicated with ellipsis ( ... ).

  • radio buttons or checkboxes can play the role of "on-off" buttons for CSS. Use radio to display one block at a time, use the checkbox when the user can expand multiple blocks simultaneously.


Functional demonstration

Starting from the above concepts, let's apply a little more CSS and build a functional prototype:

  • white-space:nowrap causes the text to not break, forcing it to cut at the end of <div> .

  • input:checked + p {white-space:normal} is used to make the paragraph immediately after the selected radiobutton show the whole sentence.

  • As a matter of aesthetics, we hide the radiobuttons from the screen, so we'll use a "remote control" HTML, which is <label for=""> . When you click on a label that has a for , it is as if you are clicking on the indicated element itself, activating it.

.mostrarmais p {
  width:200px;
  overflow:hidden;
  text-overflow:ellipsis;
  white-space:nowrap;
  margin:5px 0 0 0;
}

.mostrarmais input {
  display:none;
  position:absolute;
  left:-1000px;
}

.mostrarmais input:checked + p {
  white-space:normal;
}

.mostrarmais input:checked + p + label {
  display:none;
}

label {
  color:#fff;
  background:#39f;
  margin:0;
}

* {}
<div class="mostrarmais">
  <input type="radio" name="mostrarmais" id="m1">
  <p>Texto longo que vai ser escondido com CSS usando a propriedade overflow</p>
  <label for="m1">Mostrar mais</label>
  <input type="radio" name="mostrarmais" id="m2">
  <p>Texto longo que vai ser escondido com CSS usando a propriedade overflow</p>
  <label for="m2">Mostrar mais</label>
  <input type="radio" name="mostrarmais" id="m3">
  <p>Texto longo que vai ser escondido com CSS usando a propriedade overflow</p>
  <label for="m3">Mostrar mais</label>
  <input type="radio" name="mostrarmais" id="m0" checked="checked">
  <p></p>
  <label for="m0">Esconder tudo</label>
</div>
    
01.02.2016 / 02:01