Skip to content

Instantly share code, notes, and snippets.

@Rahmanism
Created January 29, 2023 07:45
Show Gist options
  • Save Rahmanism/2c306f8c5395b0bf99493b64174dc104 to your computer and use it in GitHub Desktop.
Save Rahmanism/2c306f8c5395b0bf99493b64174dc104 to your computer and use it in GitHub Desktop.
HTML Custom elements
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Element</title>
<style>
h3 {
color: brown;
}
</style>
</head>
<body>
<h3>Test</h3>
<todo-item checked="true">
Todo 1
<span slot="description">Description</span>
</todo-item>
<todo-item>Todo 2</todo-item>
<todo-item>Todo 3</todo-item>
<script>
const todoItemTemplate = document.createElement("template")
todoItemTemplate.innerHTML = `
<style>
div {
color: #176412;
}
.description {
color: #777;
font-size: .75rem;
font-weight: lighter;
margin: .5rem;
}
</style>
<div>
<input type="checkbox" />
<slot></slot>
<span class="description">
<slot name="description"></slot>
</span>
</div>
`
class TodoItem extends HTMLElement {
constructor() {
super()
const shadow = this.attachShadow({ mode: 'open' })
shadow.append(todoItemTemplate.content.cloneNode(true))
this.checkbox = shadow.querySelector('input[type=checkbox]')
}
static get observedAttributes() {
return ['checked']
}
attributeChangedCallback(name, oldValue, newValue) {
console.log(name, oldValue, newValue)
if (name === 'checked') {
this.updateChecked(newValue)
}
}
connectedCallback() {
console.log('connected')
}
disconnectedCallback() {
console.log('disconnected')
}
updateChecked(value) {
this.checkbox.checked = value != null && value !== 'false'
}
}
customElements.define('todo-item', TodoItem)
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment