Sha256: ca9cbf7d671c388067db6e9364cdef1b0432f363e1d1ea8c8902317dbb45b594

Contents?: true

Size: 1.24 KB

Versions: 28

Compression:

Stored size: 1.24 KB

Contents

/**
 * Show the character counter below input fields and textareas
 */
import { AlchemyHTMLElement } from "alchemy_admin/components/alchemy_html_element"
import { translate } from "alchemy_admin/i18n"

class CharCounter extends AlchemyHTMLElement {
  static properties = {
    maxChars: { default: 60 }
  }
  connected() {
    this.translation = translate("allowed_chars", this.maxChars)
    this.formField = this.getFormField()

    if (this.formField) {
      this.createDisplayElement()
      this.countCharacters()
      this.formField.addEventListener("keyup", () => this.countCharacters()) // add arrow function to get a implicit this - binding
    }
  }

  getFormField() {
    const formFields = this.querySelectorAll("input, textarea")
    return formFields.length > 0 ? formFields[0] : undefined
  }

  createDisplayElement() {
    this.display = document.createElement("small")
    this.display.className = "alchemy-char-counter"
    this.formField.after(this.display)
  }

  countCharacters() {
    const charLength = this.formField.value.length
    this.display.textContent = `${charLength} ${this.translation}`
    this.display.classList.toggle("too-long", charLength > this.maxChars)
  }
}

customElements.define("alchemy-char-counter", CharCounter)

Version data entries

28 entries across 28 versions & 1 rubygems

Version Path
alchemy_cms-7.3.4 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.3.3 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.3.2 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.2.7 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.3.1 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.3.0 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.2.6 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.2.5 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.1.12 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.2.4 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.1.11 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.2.3 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.1.10 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.2.2 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.1.9 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.2.1 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.1.8 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.1.7 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.1.6 app/javascript/alchemy_admin/components/char_counter.js
alchemy_cms-7.1.5 app/javascript/alchemy_admin/components/char_counter.js