Truncate string on toggle in JS

I have this container which should change the color on toggle, and the strings inside it should be checked for the length. If the string is longer than 20 characters, trucate it and add "..." at the end. If it’s shorter, leave it as it is. For some reason the slice does not work correctly in my case, it seems to cut more characters than it is set… Also, I can’t seem to get the innerHTML to insert the new trucated string in place. I’m writing it in ES6 syntax, can’t get it working in the fiddle – sorry about that. Any help appreciated.

https://jsfiddle.net/kpcaufg6/2/

constructor() {
  this.container = document.querySelector(".blue-bg");
  this.string = document.querySelector(".string").innerHTML;
  this.toggle = document.querySelector(".toggle");
}
events() {
  this.toggle.addEventListener("click", () => this.toggleMe());
}

truncateString(str, num) {
  if (str.length <= num) {
    return str
  }
  return str.slice(0, num) + '...'
}

toggleMe() {
  this.container.classList.toggle(".green-bg");

  if (container.classList.contains("blue-bg") && string.length >= 20) {
    this.string = this.truncateString(this.string, 20);
  } else {
    //just return string
  }
}

2 thoughts on “Truncate string on toggle in JS”

  1. The code you present is not valid. For example, this piece of code …

    constructor() {
      this.container = document.querySelector(".blue-bg");
      this.string = document.querySelector(".string").innerHTML;
      this.toggle = document.querySelector(".toggle");
    }
    

    …lacks the function keyword. I’m not sure what it is you want to do and why in this case a constructor would be better, but here is a snippet inferred from your code. It uses event delegation, meaning that a specific handler for an element is not necessary.

    document.addEventListener("click", toggle);
    
    function toggle(evt) {
      const origin = evt.target;
      if (origin.classList.contains("toggle")) {
        const container = document.querySelector(".blue-bg, .green-bg");
        if (container.classList.contains("green-bg")) {
          container.classList.replace("green-bg", "blue-bg");
        } else {
          container.classList.replace("blue-bg", "green-bg");
        }
        const stringBoxes = document.querySelectorAll(".string");
        if (container.classList.contains("blue-bg")) {
          stringBoxes.forEach(box => {
            if (box.textContent.length >= 20) {
              box.textContent = box.textContent.slice(0, 20);
            }
          });
        }
      }
    }
    .blue-bg {
      background: lightblue;
    }
    
    .green-bg {
      background: green;
    }
    <div class="blue-bg">
      <p class="string">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Delectus eveniet libero voluptate sunt distinctio iste ex, ratione, soluta, labore dolorem laboriosam sapiente praesentium consequatur. Libero vitae odit maxime repudiandae obcaecati.
      </p>
    
      <p class="string">
        lorem
      </p>
    </div>
    
    <button class="toggle">Toggle</button>

    Alternatively, here’s a snippet using a function with closures to handle the button click.

    document.addEventListener("click", ToggleHelper());
    
    function ToggleHelper() {
      const colorClasses = ["green-bg", "blue-bg"];
      const toggleBGArr = elem => isBlue(elem) ? 
        colorClasses.slice().reverse() : colorClasses;
      const getContainer = () => document.querySelector(colorClasses.map(c => `.${c}`));
      const isBlue = elem => elem.classList.contains(colorClasses[1]);
      const textSlicer = elems =>
        elems.forEach(box =>
          box.textContent = box.textContent.length >= 20 ?
            box.textContent.slice(0, 20) : box.textContent);
          
      return evt => {
        const origin = evt.target;
        if (origin.classList.contains("toggle")) {
          const container = getContainer();
          container.classList.replace
            .apply( container.classList, toggleBGArr(container) );
          isBlue(container) && textSlicer(document.querySelectorAll(".string"));
        }
      };
    }
    .blue-bg {
      background: lightblue;
    }
    
    .green-bg {
      background: lightgreen;
    }
    <div class="blue-bg">
      <p class="string">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. 
        Delectus eveniet libero voluptate sunt distinctio iste ex, 
        ratione, soluta, labore dolorem laboriosam sapiente praesentium
        consequatur. Libero vitae odit maxime repudiandae obcaecati.
      </p>
    
      <p class="string">
        lorem
      </p>
    </div>
    
    <button class="toggle">Toggle</button>
    Reply

Leave a Comment