Last active
February 25, 2020 18:16
-
-
Save sbatson5/8d78bdd2eab5f4eb46b968eb412dba05 to your computer and use it in GitHub Desktop.
Step 5
This file contains 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 CandidateImage extends HTMLElement { | |
connectedCallback() { | |
this.shadow = this.attachShadow({ mode: 'open' }); | |
// Create an image | |
const image = new Image(); | |
// Find the right image for the provided name | |
if (this.getAttribute('name') === 'pete') { | |
image.src = 'https://cdn-candidates.com/pete.jpg'; | |
} else if (this.getAttribute('name') === 'bernie') { | |
image.src = 'https://cdn-candidates.com/bernie.jpg'; | |
} | |
// We can use appendChild just like we do the normal document | |
this.shadow.appendChild(image); | |
// If the status is `winner` then add some text | |
if (this.getAttribute('status') === 'winner') { | |
this.addWinnerText(); | |
} | |
// Add our styles | |
this.createStyles(); | |
} | |
/** | |
* Adds text to our image indicating a winner | |
*/ | |
addWinnerText() { | |
const winnerSpan = document.createElement('span'); | |
winnerSpan.classList.add('winner'); | |
winnerSpan.innerText = 'Winner!!!'; | |
this.shadow.appendChild(winnerSpan); | |
} | |
/** | |
* Create the styles for our candidates | |
* We do this as a normal string rather than using @import | |
* since it is not supported in all browsers | |
* | |
* (same for new CSSStyleSheet, which is only supported in Chrome) | |
*/ | |
createStyles() { | |
const styleTemplate = ` | |
<style> | |
.winner { | |
position: absolute; | |
color: white; | |
font-size: 30px; | |
top: 10px; | |
left: 160px; | |
height: 30px; | |
font-weight: 800; | |
text-transform: uppercase; | |
} | |
</style>`; | |
this.shadow.innerHTML = styleTemplate; | |
} | |
}; | |
/** | |
* Register our custom element | |
*/ | |
window.addEventListener('DOMContentLoaded', () => { | |
customElements.define('candidate-image', CandidateImage); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment