I'm having trouble with my Read-More code , if in some circumstances the minimum characters to display are within a tag, eg;
<div class="toggole-text">
<div>Back to School Week has been a major success in the past. The week has connected thousands of alumni with their old schools so they can inspire current students as career and education role models. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia, odio? Consequuntur expedita neque cumque necessitatibus natus, beatae modi. <br><br> Back to School Week has been a major success in the past. The week has connected thousands of alumni with their old schools so they can inspire current students as career and education role models. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia, odio? Consequuntur expedita neque cumque necessitatibus natus, beatae modi. </div>
</div>
The jQuery code does not count these characters, resulting in an unexpected result, that is, the entire content of the text will be displayed in such a way: https://jsfiddle.net/qe6dyt9n/
Because jQuery code doesn't count characters that are inside other html tags.
But if there is any text without being inside another tag except for the div <div class="toggle-text"></div>
, the code would work:
<div class="toggole-text">
Back to School Week has been a major success in the past. The week has connected thousands of alumni with their old schools so they can inspire current students as career and education role models. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia, odio? Consequuntur expedita neque cumque necessitatibus natus, beatae modi. <br><br> Back to School Week has been a major success in the past. The week has connected thousands of alumni with their old schools so they can inspire current students as career and education role models. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia, odio? Consequuntur expedita neque cumque necessitatibus natus, beatae modi.
</div>
As long as that text goes past the minimum characters var showChar = 190;
, resulting in nice functionality example: https://jsfiddle.net/qe6dyt9n/1/
But I can not be aware that these conditions will always be met, in this case it is true that the code works, because it is a code that has been thoroughly edited to the expectations that the jQuery code should receive, but in the case that other users publish a post or an article through from the text editor, such as the WYSIWYG plugin, you should know that these types of editors add to all text / characters or paragraphs within a tag according to the functionalities or styles / functions that are added to the text from that editor.
The full code or at https://jsfiddle.net/xp64zdom/
$(function() {
var showChar = 190; // How many characters are shown by default
var ellipsestext = "...";
var moretext = "Read more";
var lesstext = "Read less";
//Cut content based on showChar
if ($(".toggle-text").length) {
$(".toggle-text").each(function() {
var content = $(this).html();
console.log(content);
if(content.length > showChar) {
var contentExcert = content.substr(0, showChar);
var contentRest = content.substr(showChar, content.length - showChar);
var html = contentExcert + '<span class="toggle-text-ellipses">' + ellipsestext + ' </span> <span class="toggle-text-content"><span>' + contentRest + '</span><a href="javascript:;" class="toggle-text-link">' + moretext + '</a></span>';
$(this).html(html);
}
});
}
//Toggle content when click on read more link
$(".toggle-text-link").click(function() {
if($(this).hasClass("less")) {
$(this).removeClass("less");
$(this).html(moretext);
} else {
$(this).addClass("less");
$(this).html(lesstext);
}
$(this).parent().prev().toggle();
$(this).prev().toggle();
return false;
});
});
.toggle-text {
max-width: 400px;
}
.toggle-text-content span {
display: none;
}
.toggle-text-link {
display: block;
margin: 20px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="toggle-text">
<h4>Descripción</h4>
<div>
<p>Back to School Week has been a major success in the past. The week has connected thousands of alumni with their old schools so they can inspire current students as career and education role models. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia, odio? Consequuntur expedita neque cumque necessitatibus natus, beatae modi.</p><br>
<p>
<ul class="list-style-disc">
<li>Cuando prepara su café, utiliza lógica.</li>
<li>Cuando vas a la escuela, utiliza lógica.</li>
<li>Y hasta para invertir en un curso usted utiliza lógica.</li>
</ul>
</p><br>
<p>Back to School Week has been a major success in the past. The week has connected thousands of alumni with their old schools so they can inspire current students as career and education role models. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia, odio? Consequuntur expedita neque cumque necessitatibus natus, beatae modi.</p><br>
<p>
<ul class="list-style-disc">
<li>Usted necesita desarrollar un sitio web, lógica de programación.</li>
<li>Un software, necesita lógica de programación.</li>
<li>Un informe sensacional en Excel, lógica de programación.</li>
</ul>
Una aplicación móvil para su jefe / cliente de acceso en cualquier momento, desde cualquier lugar... necesita lógica de programación.
</p><br>
<p>Back to School Week has been a major success in the past. The week has connected thousands of alumni with their old schools so they can inspire current students as career and education role models. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia, odio? Consequuntur expedita neque cumque necessitatibus natus, beatae modi.</p><br>
<p>Back to School Week has been a major success in the past. The week has connected thousands of alumni with their old schools so they can inspire current students as career and education role models. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia, odio? Consequuntur expedita neque cumque necessitatibus natus, beatae modi.</p><br>
<p>Back to School Week has been a major success in the past. The week has connected thousands of alumni with their old schools so they can inspire current students as career and education role models. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia, odio? Consequuntur expedita neque cumque necessitatibus natus, beatae modi.</p><br>
<p>Back to School Week has been a major success in the past. The week has connected thousands of alumni with their old schools so they can inspire current students as career and education role models. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia, odio? Consequuntur expedita neque cumque necessitatibus natus, beatae modi.</p><br>
<p>Back to School Week has been a major success in the past. The week has connected thousands of alumni with their old schools so they can inspire current students as career and education role models. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia, odio? Consequuntur expedita neque cumque necessitatibus natus, beatae modi.</p><br>
<p>Back to School Week has been a major success in the past. The week has connected thousands of alumni with their old schools so they can inspire current students as career and education role models. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quia, odio? Consequuntur expedita neque cumque necessitatibus natus, beatae modi.</p><br>
</div>
<div class="heading-part">
<h4>¿Temas de interes?</h4>
<ul class="list-style-disc">
<li>Programadores.</li>
</ul>
</div>
</div>
The idea of all this work is to show the reader a certain part of a text and, through a Read-More link, display the rest of the hidden text so that the reader continues with all the reading, of course there is also the possibility of hiding the text via a Read-Less binding .
Can you explain me what changes or what code should I add to the jQuery code, so that the code counts all the characters whether those characters are only inside the div without any other tag and, likewise regardless of whether those characters are inside other tags or not counting them the same so as not to present those problems that I have detailed.
Is there that possibility of counting all the characters that are inside the div <div class="toggle-text"></div>
regardless of whether or not that text is inside other tags HTML
, either p, div, span, ul, li
or others?
The problem is that when trying to put everything in the same block, it does not distinguish between the labels that the text has as you comment.
The solution could be to split it in two. You would be left with substituting the check and adding it in two parts:
Replace:
For this:
I can think of a simple solution, by using regular expressions you could treat the entire content to remove the HTML tags it contains. In this way you would only have the text contained in that block, being able to efficiently count the number of textual characters.
Using the
div
one you give as an example but slightly altered to give it more complexity:As you can see, the content goes through several regular expressions, the first removes all the tags, the second removes the carriage returns and line feeds left by the first, and the last is a call to the function
trim()
, which removes the spaces in white at the beginning and end of the string.In this way you would get a fairly exact number of characters of clean text. It is not really exact because between the contents of different
divs
ones we would have a space left (an extra character for eachdiv
internal), but I think it is precise enough to create a Read more system like the one you expose us to.You can use
.textContent
on the parent element, and then replace multiple spaces, tabs, and newlines with a regexp to get the number of characters.A practical example using the MDN web docs editor that shows the difference between counting html characters (formatted summary) and counting untagged characters (show raw summary):
In both cases summary/fulltext are displayed as two different divs, based on the state of one
checkbox
and with twolabels
for each (variation of https://es.stackoverflow.com/a/187565/81450 )En vez de contarlos, la pregunta que yo veo es la siguiente: ¿Cómo limitar un contenido HTML a una determinada cantidad de caracteres de texto plano? La solución es mirar caracter por caracter y ver si cumplen las condiciones para ser contado como texto plano.
La estructura HTML de un texto de ejemplo es la siguiente:
texto
ocultado
mostrado
(esta clase se genera mediante jQuery)Lo que hace el jQuery es agarrar el texto ocultado, cortarlo y mostrar la parte cortada. Cuando se hace click en Leer más, muestra el texto completo agregando la clase
mostrado
altexto
, que lo extrae desde la claseocultado
, que es uno de los hijos del padre del botón Leer más o Leer menos. Al clickear en Leer menos, corta nuevamente el texto, extrayendo desdeocultado
.Entonces queda generado mediante jQuery de la siguiente manera:
Al iniciar la página, es automático el proceso de agregar el texto mostrado a partir del oculto, y agregar el enlace que simula ser un botón mediante un
preventDefault
en elonclick
.Clickear en el enlace, lo que hará es buscar al padre, mediante
$(this).parent()
, luego se busca el texto ocultado mediantepadre.find(".ocultado").html()
y si es necesario cortarlo, llama a una función propia que va agregando caracteres uno por uno hasta que la cantidad de caracteres planos es la cantidad solicitada, que en mi caso esvar cantidad_caracteres = 10
.Las condiciones para que un caracter sea plano son las siguientes:
No es el principio de la línea, es decir, que no se cuentan espacios, tabuladores, o saltos de línea (
\x20
,\x09
o\x0A
respectivamente) si es el principio de línea. Un principio de línea empieza con un salto de línea.Si el último caracter agregado es espacio (
\x20
,\x09
o\x0A
), el siguiente espacio se considera duplicado y entonces no es plano (es decir, plano son los contados). Los duplicados, lógicamente solo se pueden contar luego de haber agregado el primer caracter.Si el caracter es especial, no es plano. Con especial me refiero al signo de cierre de etiqueta, el signo mayor (
>
).Las aperturas (
<
) y los cierres (>
) de una etiqueta tienen que estar balanceados. Para esto se usa un contador,var balance = 0
, al encontrar una apertura, suma en 1, al encontrar un cierre, resta 1, es decir, incrementa y decrementa. Al estar el balance en 0, puede contarlo como plano.Código completo: