0

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
  }
}
5
  • Not really sure what you mean by / think you mean by "ES6 syntax" - but that's not how you define js functions and because of that you're getting syntax errors in your fiddle SyntaxError: Unexpected token '{' Commented Feb 15, 2021 at 11:09
  • yeah I'm going through this tutorial, and the instructor says that using constructor etc. is a "better" way of writing the JS... Can't figure out which semicolon is missing though Commented Feb 15, 2021 at 11:13
  • 1
    Yes, you can namespace functions and use a constructor, but that's not how you do it. Try these stackoverflow.com/search?q=%5Bjavascript%5D+constructor+pattern Commented Feb 15, 2021 at 11:19
  • Do you have a link to the tutorial? Might be able to point out the bit you're missing in your own context. Commented Feb 15, 2021 at 11:21
  • Thanks I will look into it it seems helpful, tutorial is not public one Commented Feb 15, 2021 at 11:24

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

Comments

1

Could you try this please. It may helpful for you :)

$(document).ready(function() {
  $(".buttonclick").click(function() {
    var myStr = $(".textarea").text();
    var limit = 20;
    if (myStr.length > limit && $('.textarea').hasClass('bg-green')) {
      var strtemp = myStr.substr(0, limit);
      $(".textarea").text(strtemp + '.....');
      $(".textarea").css('background-color', '#0f0');

    }
  });
});
.textarea {
  width: 450px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3>Enter Text and Click the Buttons</h3>
<div class="textarea bg-green">Paragraph of text with multiple white spaces before and after. </div>
<br>
<button type="button" class="buttonclick">click</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.