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
}
}
The code you present is not valid. For example, this piece of code …
…lacks the
function
keyword. I’m not sure what it is you want to do and why in this case aconstructor
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.Alternatively, here’s a snippet using a function with closures to handle the button click.
tadalafil 40 mg – buy tadalafil generic online online tadalafil