Skip to content

Instantly share code, notes, and snippets.

@loloof64
Created September 27, 2019 11:20
Show Gist options
  • Save loloof64/4ab5b0b4ef84b344207d78b32dc367e0 to your computer and use it in GitHub Desktop.
Save loloof64/4ab5b0b4ef84b344207d78b32dc367e0 to your computer and use it in GitHub Desktop.
Udemy Web comppnent course - Exercise 1
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Web Components</title>
<script src="MyButton.js"></script>
</head>
<body>
<loloof64-paragraph></loloof64-paragraph>
</body>
</html>
class MyButton extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open'});
this.shadowRoot.innerHTML = `
<button>Show</button>
<p id="info-box">More infos!</p>
<style>
#info-box {
display: none;
}
</style>
`;
this._isHidden = true;
}
connectedCallback() {
const button = this.shadowRoot.querySelector('button');
button.addEventListener('click', this._toggleParagraphVisibility);
}
_toggleParagraphVisibility = () => {
const button = this.shadowRoot.querySelector('button');
const infoEl = this.shadowRoot.querySelector('p');
if (this._isHidden) {
infoEl.style.display = 'block';
button.textContent = 'Hide';
this._isHidden = false;
} else {
infoEl.style.display = 'none';
button.textContent = 'Show';
this._isHidden = true;
}
}
}
customElements.define('loloof64-paragraph', MyButton);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment