Created
May 24, 2017 01:16
-
-
Save shalotelli/0bad54fcd8cefcfa7511170b19c290c8 to your computer and use it in GitHub Desktop.
Creating Web Components in JavaScript (ES6) to use in your Angular, React and Ember projects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Web Components</title> | |
<style> | |
body { | |
font-family: 'Helvetica Neue'; | |
} | |
</style> | |
<script src="progressbar.js"></script> | |
</head> | |
<body> | |
<h1>Web Components</h1> | |
<progress-bar></progress-bar> | |
<script> | |
(function() { | |
var progress = document.querySelector('progress-bar'), | |
complete = 0; | |
var progressInterval = setInterval(() => { | |
complete += 1; | |
if (complete <= 100) { | |
progress.setAttribute('complete', complete); | |
} else { | |
clearInterval(progressInterval); | |
} | |
}, 100); | |
})(); | |
</script> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ProgressBar extends HTMLElement { | |
constructor() { | |
super(); | |
this.shadow = this.createShadowRoot(); | |
this._complete = 0; | |
} | |
get complete() { | |
return this._complete; | |
} | |
set complete(val) { | |
this.setAttribute('complete', val); | |
} | |
static get observedAttributes() { | |
return [ 'complete' ]; | |
} | |
attributeChangedCallback(name, oldVal, newVal) { | |
var innerBar = this.shadow.querySelector('.progress-bar-inner'); | |
switch(name) { | |
case 'complete': | |
this._complete = parseInt(newVal, 10) || 0; | |
innerBar.style.width = this.complete + '%'; | |
innerBar.innerHTML = this.complete + '%'; | |
} | |
} | |
connectedCallback() { | |
var template = ` | |
<style> | |
.progress-bar { | |
width: 50%; | |
height: 30px; | |
background-color: #EDF2F4; | |
border-radius: 5px; | |
color: #FFF; | |
} | |
.progress-bar-inner { | |
height: 100%; | |
line-height: 30px; | |
background: #2B2D42; | |
text-align: center; | |
border-radius: 5px; | |
transition: width 0.25s; | |
} | |
</style> | |
<div class="progress-bar"> | |
<div class="progress-bar-inner">${this.complete}%</div> | |
</div> | |
`; | |
this.shadow.innerHTML = template; | |
} | |
} | |
window.customElements.define('progress-bar', ProgressBar); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment