Browse Source

add HTML

develop
Carmine De Rosa 5 years ago
parent
commit
f1ccebbdfa
  1. 5
      .gitignore
  2. 1
      html/TODO
  3. 15
      html/index.html
  4. 96
      html/ratings.js

5
.gitignore

@ -0,0 +1,5 @@
react/node_modules/
react/package-lock\.json
storybook/node_modules/
storybook/package-lock\.json

1
html/TODO

@ -0,0 +1 @@
Open in browser...

15
html/index.html

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test my-rating WebComponent</title>
<script src="https://code.jquery.com/jquery-3.4.1.slim.js" integrity="sha256-BTlTdQO9/fascB1drekrDVkaKd9PkwBymMlHOiG+qLI=" crossorigin="anonymous"></script>
<script src="https://unpkg.com/@webcomponents/webcomponentsjs@2.0.0/webcomponents-loader.js"></script>
<script src="ratings.js"></script>
</head>
<body>
<my-rating id="myRatingComponent" max-value="6" value="2"></my-rating>
</body>
</html>

96
html/ratings.js

@ -0,0 +1,96 @@
const styleRules = ` .rating {font-size: 50px; color: orange; cursor: pointer }`
class MyRating extends HTMLElement {
constructor() {
super()
this._maxValue = 5
this._value = 4
this.attachShadow({mode: "open"})
}
connectedCallback() {
this.createComponent()
}
get maxValue() {
return this._maxValue
}
set maxValue(val) {
this._maxValue = val
this.setAttribute("max-value", val)
}
get value() {
return this._value
}
set value(val) {
this._value = val
this.setAttribute("value", val)
}
static get observedAttributes() {
return ["max-value", "value"]
}
attributeChangedCallback(name, oldValue, newValue) {
if (oldValue !== newValue) {
switch (name) {
case "max-value":
this._maxValue = newValue
break
case "value":
this._value = newValue
break
default:
}
this.replaceStarList()
}
}
replaceStarList() {
let starNode = this.shadowRoot.children[1];
if (starNode) {
let starList = this.createStarList();
starNode.remove();
this.shadowRoot.appendChild(starList);
}
}
createComponent() {
this.createStyle()
let starList = this.createStarList()
this.shadowRoot.appendChild(starList)
}
createStyle() {
let style = document.createElement("style")
style.appendChild(document.createTextNode(styleRules))
this.shadowRoot.appendChild(style)
}
createStarList() {
let div = document.createElement("div")
for (let i = 1; i <= this.maxValue; i++) {
let star = i <= this.value ? this.createStar("&#x2605", i) : this.createStar("&#x2606", i)
div.appendChild(star)
}
return div
}
createStar(starCode, i) {
let span = document.createElement("span")
span.setAttribute("class", "rating")
span.innerHTML = starCode
span.addEventListener("click", () => {
this.value = i
}, false)
return span
}
}
customElements.define("my-rating", MyRating)
Loading…
Cancel
Save