Limit of characters in a DIV

1

How can I limit the amount of characters that will be inserted into a div?

    
asked by anonymous 21.10.2016 / 18:30

3 answers

3

Due to lack of information, I will put a solution achieved via jquery : In other words, a short answer to a short question.

var divXpto = $('#id_da_sua_div');
divXpto.text(divXpto.text().substring(0,300));
    
21.10.2016 / 18:35
1

If it is an input, you have two solutions:

Check the amount of characters in the input and / or leave unlimited and use the following code when the user inserts.

  function toLimit(string = ""){
        string.value = string.value.substring(0,10);
    }
<input type="text" onkeyup="toLimit(this)" />

Let's say the input value is Hello world! This is a function to limit the text

The result will be something like "Hello world!"

    
21.10.2016 / 18:40
0

If you have a language on the serverside, such as eg. php, it is better to make the substring before sending the complete content to the browser, but if this is not an option, or if you want to allow the user to see the text that was omitted if he wants, here's a way to do with jquery:

var leiamais_limit = 60;

$('.leiamais').each(function() {
  var html = $(this).html();
  if (html.length > leiamais_limit) $(this).html(html.substring(0, leiamais_limit) + '<a href="#" class="leiamais-btn">... [leia mais]</a><span class="leiamais-tail">' + html.substring(leiamais_limit) + '</span>');
}).on('click', '.leiamais-btn', function() {
  $(this).hide().siblings('.leiamais-tail').show();
});
.leiamais {
  padding: 10px;
}
.leiamais-btn {
  font-size: 80%;
  color: inherit;
  text-decoration: none;
}
.leiamais-tail {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="leiamais">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut sed commodo arcu. Vestibulum euismod nunc tortor, eu tempor urna suscipit eget. Pellentesque nec nunc et nunc vehicula elementum. Vivamus dictum eu quam sit amet sollicitudin.</div>
<div class="leiamais">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</div>
<div class="leiamais">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut sed commodo arcu. Vestibulum euismod nunc tortor, eu tempor urna suscipit eget. Pellentesque nec nunc et nunc vehicula elementum. Vivamus dictum eu quam sit amet sollicitudin. In dapibus enim
  quis tortor eleifend, in hendrerit turpis dignissim. Suspendisse pretium cursus massa, a hendrerit ex lacinia et. Suspendisse tincidunt ultricies nulla, vel auctor arcu vehicula at.</div>
    
22.10.2016 / 01:22