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
}
}
SyntaxError: Unexpected token '{'namespacefunctions and use a constructor, but that's not how you do it. Try these stackoverflow.com/search?q=%5Bjavascript%5D+constructor+pattern