Reputation: 121
I'm trying to add a simple "Read more" button to a page. I managed to prepare a working function that hides the maximum characters within an element. And to call the function I've prepared a button in the HTML with a "onclick" event to call the function.
Now a couple things happen that shouldn't. The button should reveal the hidden text but the opposite happens and everytime the button is clicked more characters are removed until I'm left with only the dots even though I have a var that limits the characters to 15. I have spent too much time trying to figure this out knowing this is probably basic jQuery. I apologize if that is the case I just hope someone can point out what I'm doing wrong here.
HTML:
<button class="content-toggle" onclick="textCollapse()">Read more</button>
jQuery:
function textCollapse() {
var limit = 15;
var chars = jQuery(".field-content p").text();
if (chars.length > limit) {
var visiblePart = jQuery("<span class='visiblepart'> "+ chars.substr(0, limit) +"</span>");
var dots = jQuery("<span class='dots'>... </span>");
jQuery(".field-content p").toggle()
.empty()
.append(visiblePart)
.append(dots)
}
};
Upvotes: 1
Views: 1083
Reputation: 105547
I would save full text content into outer variable and keep it there. There is no need to requery text content every time a button is clicked. Also, it's better to have a variable that would store a state for the text - collapsed or not instead of comparing each time.
var fullText = jQuery(".field-content p").text();
var collapsed = false;
function textCollapse() {
var limit = 15;
if (collapsed) {
var visiblePart = jQuery("<span class='visiblepart'> " + fullText + "</span>");
jQuery(".field-content p")
.empty()
.append(visiblePart)
collapsed = false;
} else {
var visiblePart = jQuery("<span class='visiblepart'> " + fullText.substr(0, limit) + "</span>");
var dots = jQuery("<span class='dots'>... </span>");
jQuery(".field-content p")
.empty()
.append(visiblePart)
.append(dots)
collapsed = true;
}
}
Also, I don't think you need to call toggle()
since all operations are performed synchronously and there's no need to hide p
element before emptying and appending nodes.
Upvotes: 2