Skip to content
Snippets Groups Projects

Adjust trimLength if HTML has extra characters

@@ -46,7 +46,7 @@
Drupal.ExpandCollapseFormatter = function ecfConstructor(field, delta) {
this.id = `expand-collapse-${delta}`;
this.content = field.querySelector('.ec-content');
this.trimLength = field.getAttribute('data-trim-length');
this.trimLength = parseInt(field.getAttribute('data-trim-length'));
this.state = field.getAttribute('data-default-state');
this.linkTextOpen = field.getAttribute('data-link-text-open');
this.linkTextClose = field.getAttribute('data-link-text-close');
@@ -54,14 +54,20 @@
this.linkClassClose = field.getAttribute('data-link-class-close');
this.text = this.content.innerText;
this.html = this.content.innerHTML;
this.textHtmlDifference = this.content.innerHTML.length - this.content.innerText.length;
this.showMore = Drupal.t(this.linkTextOpen);
this.showLess = Drupal.t(this.linkTextClose);
if (this.textHtmlDifference > 0) {
// If there's HTML, add the char count of the difference,
// to not trim the HTML too early.
this.trimLength = this.trimLength + this.textHtmlDifference;
}
// Set an id for the field element.
field.setAttribute('id', this.id);
// Create a read more link and initiate the toggle.
if (this.text.length > this.trimLength) {
if (this.html.length > this.trimLength) {
this.toggleLink = document.createElement('a');
this.toggleLink.innerHTML = this.showMore;
this.toggleLink.setAttribute('href', `#${this.id}`);
Loading