Javascript: Custom Element
Custom Element alias Web Component
Beberapa studi kasus memungkinkan kita membuat custom html element untuk memudahkan interaksi tertentu, bahkan mengolah data dinamis. Elemen ini dapat kita kondisikan dengan fungsi dan kegunaan tertentu. Bagaimana membuatnya? Kita akan coba bikin contoh simplenya:
- Pertama buat file WordBody.js
- Masukkan ke file html dengan tag script <script src="js/WordBody.js"></script>
- Lalu gunakan seperti box model element contoh: <word-body></word-body>
// WordBody.js
class WordBody extends HTMLParagraphElement {
constructor() {
// Always call super first in constructor
super();
// Element functionality here
// Properties and Method should be declared befoore use
// ...
}
static get observedAttributes() { return ['width', 'height']; }
connectedCallback(){
// Element on render
}
attributeChangedCallback(name, oldValue, newValue) {
// Element attribute on change (contohnya: height/width seperti yang terobservasi di atas)
}
adoptedCallback() {
// Element on moved
}
disconnectedCallback(){
// Element on destroy
}
}
customElements.define('word-body', WordBody, { extends: 'p' });
Dimana elemen yang tersedia untuk dikustom terdiri dari:
- <article>
- <aside>
- <blockquote>
- <body>
- <div>
- <footer>
- <h1>
- <h2>
- <h3>
- <h4>
- <h5>
- <h6>
- <header>
- <main>
- <nav>
- <p>
- <section>
- <span>
Nah, langsung saja untuk bikin contoh custom element yang jalan mirip seperti collapse button nya bootstrap. Requirement nya setiap hide button di klik akan menampilkan text yang ada di dalam tag, dan akan menyembunyikan text setiap show button diklik, tag digunakan seperti berikut: <my-collapse-button>Contoh text yang disembunyikan dan dapat ditampilkan jika tombol diklik</my-collapse-button>
class CollapseButton extends HTMLElement {
constructor() {
super()
console.log('my-collapse-button is instantiated')
this.attachShadow({ mode: 'open' })
this.shadowRoot.innerHTML =
`
<style>
button { padding: 1em 2em; font-size: 16px; line-height: 1.5; border: none; outline: none; background: cyan; color: grey;}
</style>
<button>Show</button>
<p style="display: none;"><slot></slot></p>`
this._showContent
this._isHidden
this.actionButton = this.shadowRoot.querySelector('button')
this.textInfo = this.shadowRoot.querySelector('p')
}
connectedCallback() {
this.actionButton.addEventListener('click', this._showContent.bind(this))
this._isHidden = true
}
_showContent() {
if (this._isHidden) {
this.textInfo.style.display = 'block'
this.actionButton.textContent = 'Hide'
this._isHidden = false
} else {
this.actionButton.textContent = 'Show'
this.textInfo.style.display = 'none'
this._isHidden = true
}
}
}
customElements.define('my-collapse-button', CollapseButton)