Connect read more button with database to expand / collapse rich text

Hello ! I’m currently designing a website which displays hundreds of releases from a record music company. So I’m using dynamic pages and databases in order to create each page, which usually contains an image, a video, an audio, and of course, a text that describes the album, vinyl or whatever.

My problem is the following : some of the texts are pretty long (sometimes more than 1500 characters) so I need to connect a read more / read less button in order to expand or collapse text when clicked. I used a code on other pages that works fine (see below), but I can’t figure out a solution to connect this button to the different texts of my database.

Also, I’d like to make that button appear on concerned pages only when the text contains a certain number of character (1000 more or less). Don’t know if that is possible, but I’d really appreciate any help !

let fullText ; // variable to hold the full text
let shortText ; // variable to hold the short version of the text

$w . onReady ( function () {
// how many characters to include in the shortened version
const shortTextLength = 40 ; // you can change this number
// read the full text and store it in the fullText variable
fullText = $w ( “#myTextElement” ). text ;
// grab the number of characters defined in shortTextLength and store them in the shortText variable
shortText = fullText . substr ( 0 , shortTextLength ) + “…” ;
// set the contents of the text element to be the short text
$w ( “#myTextElement” ). text = shortText ;
});

// check the contents of the text element
if ( $w ( “#myTextElement” ). text === shortText ) {
// if currently displaying short text, display the full text
$w ( “#myTextElement” ). text = fullText ;
$w ( “#myButton” ). label = “Show less” ;
} else {
// if currently displaying full text, display the short text
$w ( “#myTextElement” ). text = shortText ;
$w ( “#myButton” ). label = “Show more” ;
}
}

https://www.wix.com/corvid/forum/community-discussion/creating-a-show-more-button-for-a-text

Woow thank you so much @GOS !! I didn’t check that post on the forum but this is just what I needed !

Actually there is still one small issue. As I’m working with rich text, I replaced the .text by .html in the code provided on the forum. But for some reason, a few pages are not displaying text as it should when collapsed… I’m posting a caption just below so you can see what I mean. Do you have any idea on how to remove that ?