I am new to Javascript and I am trying to create something relatively simple.
I have an HTML file with the following div in it:
<p id="textArea" class = "more"> </p>
I want to make a Javascript function that takes the text inside this div, breaks it into words and shows only as many words as I select. I also want to add a โsee moreโ link at the end of the shortened text, which I can click to switch between the full and shortened versions of the text.
My function looks like this:
function expandContent() { var showChar = 30; var ellipsesText = "..."; var moreText = "(read more)"; var lessText = "(read less)"; $('.more').each(function() { var $this = $(this); var fullText = $this.text().split(" "); if (fullText.length > showChar) { var shortText = fullText.slice(0, showChar); shortText.push('...'); shortText = shortText.join(separator=' '); $this.data("full", fullText.join(separator=' ')) .stop() .data("state", "shortState") .stop() .data("short", shortText) .stop() .html(shortText); $('<a />', { class: 'record-brief-more-link', text: moreText, href: '#' }).appendTo($this); } }); $(".record-brief-more-link").on('click', function() { var $text = $(this).closest('.more'); var state = $text.data("state"); var linkText = (state == "shortState") ? lessText : moreText; $(this).text(linkText); $text.html($text.data((state == "shortState") ? "full" : "short")); $text.data("state", (state == "shortState") ? "fullState" : "shortState"); });};
The problem is that after I click the link once, I get the full text as expected, but the link is no longer visible, so I canโt go back to the shortened text if I want. Does anyone know why this is happening?
Rayan source share