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

Asked

Viewed 2,050 times

10

Hello, I am developing a system where will be publications, but I would like that, in each publication, shows "x" characters, and passing of this value, shows a button written "Show more", same as Facebook.

If anyone knows how to do that I’ll be very grateful.

Example:

Lorem ipsum dolor sit Amet, consectetur adipiscing Elit. In sed dolor molestie, suscipit quam in, efficitur ante. Praesent feugiat rhoncus Tellus, in rhoncus nisl...
Show more

2 answers

9

Using CSS

CSS doesn’t have a specific way to count "x" characters, but there are some things that can help you out a bit:

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

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

  • radio Buttons or checkboxes can play the role of "on-off" buttons for CSS.

    Use the radio for when displaying one block at a time, use the checkbox when the user can expand several blocks simultaneously.


Functional demonstration

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

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

  • the input:checked + p {white-space:normal} serves to have the paragraph immediately following the radiobutton selected show the whole sentence.

  • for the sake of aesthetics, we hide the radiobuttons from the screen, so let’s use an HTML "remote control", which is the <label for="">. When you click on one label who has a for, it is as if you were clicking on the given 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>

  • 1

    Man, you really helped me, thank you!

  • @pxntxs. has other ways, I tried to show with pure CSS for you to take the basic ideas, and adapt to your real case. The important thing is you understand how it works.

  • I get it. Thank you very much!

7


First of all, 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 height complete.
  • Use a script to "cut" the text and save the original, which will be displayed again when clicking the button or link.
  • Render the original hidden text and the cut text visible and simply change the elements by clicking on the link.
  • Render the page with the cut text and load the full content via Ajax.

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

The approach may 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, that a little more text increasing the page size is no problem for you and that you really want to limit by number of characters, the second or third options are more reasonable.

Example

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

Cut in text makes a regular expression search to count the amount of spaces until you find the umpteenth 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>
<div class="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>

  • 1

    Thanks for the explanation, I’m a layman in JS but I’ll do my best to learn.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.