<p>In my last article, we saw that web components aren’t as scary as they seem. We looked at a super simple setup and made a zombie dating service profile, complete with a custom element. We reused the element for each profile and populated each one with unique info using the element. </p> <p>Here’s how it all came together. </p> <p>CodePen Embed Fallback </p> <p>That was cool and a lot of fun (well, I had fun anyway…), but what if we take this idea one step further by making it interactive. Our zombie profiles are great, but for this to be a useful, post-apocalyptic dating experience you’d want to, you know, “Like” a zombie or even message them. That’s what we’re going to do in this article. We’ll leave swiping for another article. (Would swiping left be the appropriate thing for zombies?) </p> <p>This article assumes a base level of knowledge about web components. If you’re new to the concept, that’s totally fine — the previous article should give you everything you need. Go ahead. Read it. I’ll wait. *Twiddles thumbs* Ready? Okay. </p> <p>First, an update to the original version </p> <p>Let’s pause for one second (okay, maybe longer) and look at the ::slotted() pseudo element. It was brought to my attention after the last article went out (thanks, Rose!) and it solves some (though not all) of the encapsulation issues I encountered. If you recall, we had some CSS styles outside of the component’s and some inside a element within the . The styles inside the were encapsulated but the ones outside were not. </p> <p>But that’s where ::slotted comes into play. We declare an element in the selector like so: </p> <p>::slotted(img) {<br /> width: 100%;<br /> max-width: 300px;<br /> height: auto;<br /> margin: 0 1em 0 0;<br /> } </p> <p>Now, any element placed in any slot will be selected. This helps a lot! </p> <p>But this doesn’t solve all of our encapsulation woes. While we can select anything directly in a slot, we cannot select any descendant of the element in the slot. So, if we have a slot with children — like the interests section of the zombie profiles — we’re unable to select them from the element. Also, while ::slotted has great browser support, some things (like selecting a pseudo element, e.g., ::slotted(span)::after) will work in some browsers (hello, Chrome), but won’t work in others (hello, Safari). </p> <p>So, while it’s not perfect, ::slotted does indeed provide more encapsulation than what we had before. Here’s the dating service updated to reflect that: </p> <p>CodePen Embed Fallback </p> <p>Back to interactive web components! </p> <p>First thing I’d like to do is add a little animation to spice things up. Let’s have our zombie profile pics fade in and translate up on load. </p> <p>When I first attempted this, I used img and ::slotted(img) selectors to directly animate the image. But all I got was Safari support. Chrome and Firefox would not run the animation on the slotted image, but the default image animated just fine. To get it working, I wrapped the slot in a div with a .pic class and applied the animation to the div instead. </p> <p>.pic {<br /> animation: picfadein 1s 1s ease-in forwards;<br /> transform: translateY(20px);<br /> opacity: 0;<br /> } </p> <p>@keyframes picfadein {<br /> from { opacity: 0; transform: translateY(20px); }<br /> to { opacity: 1; transform: translateY(0); }<br /> } </p> <p>CodePen Embed Fallback </p> <p>“Liking” zombies </p> <p>Wouldn’t it be something to “Like” that cute zombie? I mean from the user’s perspective, of course. That seems like something an online dating service ought to have at the very least. </p> <p>We’ll add a checkbox “button” that initiates a heart animation on click. Let’s add this HTML at the top of the .info div: </p> <p>Like </p> <p>Here’s a heart SVG I pulled together. We know that Zombies love things to be terrible, so their heart will be an eye searing shade of chartreuse: </p> <p>Here’s the important bits of the CSS that are added to the template’s element: </p> <p>#trigger:checked + .likebtn {<br /> /* Checked state of the .likebtn. Flips the foreground/background color of the unchecked state. */<br /> background-color: #960B0B;<br /> color: #fff;<br /> } </p> <p>#trigger {<br /> /* With the label attached to the input with the for attribute, clicking the label checks/unchecks the box, so we can remove the checkbox. */<br /> display: none;<br /> } </p> <p>.heart {<br /> /* Start the heart off so small it&#8217;s nigh invisible */<br /> transform: scale(0.0001);<br /> } </p> <p>@keyframes heartanim {<br /> /* Heart animation */<br /> 0% { transform: scale(0.0001); }<br /> 50% { transform: scale(1); }<br /> 85%, 100% { transform: scale(0.4); }<br /> } </p> <p>#trigger:checked ~ .heart {<br /> /* Checking the checkbox initiates the animation */<br /> animation: 1s heartanim ease-in-out forwards;<br /> } </p> <p>Pretty much standard HTML and CSS there. Nothing fancy or firmly web-component-ish. But, hey, it works! And since it’s technically a checkbox, it’s just as easy to “unlike” a zombie as it is to “Like” one. </p> <p>CodePen Embed Fallback </p> <p>Messaging zombies </p> <p>If you’re a post-apocalyptic single who’s ready to mingle, and see a zombie whose personality and interests match yours, you might want to message them. (And, remember, zombies aren’t concerned about looks — they’re only interested in your braaains.) </p> <p>Let’s reveal a message button after a zombie is “Liked.” The fact that the Like button is a checkbox comes in handy once again, because we can use its checked state to conditionally reveal the message option with CSS. Here’s the HTML added just below the heart SVG. It can pretty much go anywhere as long as it’s a sibling of and comes after the #trigger element. </p> <p>Message </p> <p>Once the #trigger checkbox is checked, we can bring the messaging button into view: </p> <p>#trigger:checked ~ .messagebtn {<br /> display: block;<br /> } </p> <p>We’ve done a good job avoiding complexity so far, but we’re going to need to reach for a little JavaScript in here. If we click the message button, we’d expect to be able to message that zombie, right? While we could add that HTML to our , for demonstration purposes, lets use some JavaScript to build it on the fly. </p> <p>My first (naive) assumption was that we could just add a element to the template, create an encapsulated script, and be on our merry way. Yeah, that doesn’t work. Any variables instantiated in the template get instantiated multiple times and well, JavaScript’s cranky about variables that are indistinguishable from each other. *Shakes fist at cranky JavaScript* </p> <p>You probably would have done something smarter and said, “Hey, we’re already making a JavaScript constructor for this element, so why wouldn’t you put the JavaScript in there?” Well, I was right about you being smarter than me. </p> <p>Let’s do just that and add JavaScript to the constructor. We’ll add a listener that, once clicked, creates and displays a form to send a message. Here’s what the constructor looks like now, smarty pants: </p> <p>customElements.define(&#8216;zombie-profile&#8217;,<br /> class extends HTMLElement {<br /> constructor() {<br /> super();<br /> let profile = document.getElementById(&#8216;zprofiletemplate&#8217;);<br /> let myprofile = profile.content;<br /> const shadowRoot = this.attachShadow({<br /> mode: &#8216;open&#8217;<br /> }).appendChild(myprofile.cloneNode(true)); </p> <p> // The &#8220;new&#8221; code<br /> // Grabbing the message button and the div wrapping the profile for later use<br /> let msgbtn = this.shadowRoot.querySelector(&#8216;.messagebtn&#8217;),<br /> profileEl = this.shadowRoot.querySelector(&#8216;.profile-wrapper&#8217;); </p> <p> // Adding the event listener<br /> msgbtn.addEventListener(&#8216;click&#8217;, function (e) { </p> <p> // Creating all the elements we&#8217;ll need to build our form<br /> let formEl = document.createElement(&#8216;form&#8217;),<br /> subjectEl = document.createElement(&#8216;input&#8217;),<br /> subjectlabel = document.createElement(&#8216;label&#8217;),<br /> contentEl = document.createElement(&#8216;textarea&#8217;),<br /> contentlabel = document.createElement(&#8216;label&#8217;),<br /> submitEl = document.createElement(&#8216;input&#8217;),<br /> closebtn = document.createElement(&#8216;button&#8217;); </p> <p> // Setting up the form element. The action just goes to a page I built that spits what you submitted back at you<br /> formEl.setAttribute(&#8216;method&#8217;, &#8216;post&#8217;);<br /> formEl.setAttribute(&#8216;action&#8217;, &#8216;https://johnrhea.com/undead-form-practice.php&#8217;);<br /> formEl.classList.add(&#8216;hello&#8217;); </p> <p> // Setting up a close button so we can close the message if we get shy<br /> closebtn.innerHTML = &#8220;x&#8221;;<br /> closebtn.addEventListener(&#8216;click&#8217;, function () {<br /> formEl.remove();<br /> }); </p> <p> // Setting up form fields and labels<br /> subjectEl.setAttribute(&#8216;type&#8217;, &#8216;text&#8217;);<br /> subjectEl.setAttribute(&#8216;name&#8217;, &#8216;subj&#8217;);<br /> subjectlabel.setAttribute(&#8216;for&#8217;, &#8216;subj&#8217;);<br /> subjectlabel.innerHTML = &#8220;Subject:&#8221;;<br /> contentEl.setAttribute(&#8216;name&#8217;, &#8216;cntnt&#8217;);<br /> contentlabel.setAttribute(&#8216;for&#8217;, &#8216;cntnt&#8217;);<br /> contentlabel.innerHTML = &#8220;Message:&#8221;;<br /> submitEl.setAttribute(&#8216;type&#8217;, &#8216;submit&#8217;);<br /> submitEl.setAttribute(&#8216;value&#8217;, &#8216;Send Message&#8217;); </p> <p> // Putting all the elments in the Form<br /> formEl.appendChild(closebtn);<br /> formEl.appendChild(subjectlabel);<br /> formEl.appendChild(subjectEl);<br /> formEl.appendChild(contentlabel);<br /> formEl.appendChild(contentEl);<br /> formEl.appendChild(submitEl); </p> <p> // Putting the form on the page<br /> profileEl.appendChild(formEl);<br /> });<br /> }<br /> }); </p> <p>So far, so good! </p> <p>CodePen Embed Fallback </p> <p>Before we call it a day, there’s one last thing we need to address. There’s nothing worse than that first awkward introduction, so lets grease those post-apocalyptic dating wheels by adding the zombie’s name to the default message text. That’s a nice little convenience for the user. </p> <p>Since we know that the first span in the element is always the zombie’s name, we can grab it and stick its content in a variable. (If your implementation is different and the elements’s order jumps around, you may want to use a class to ensure you always get the right one.) </p> <p>let zname = this.getElementsByTagName(&#8220;span&#8221;)[0].innerHTML; </p> <p>And then add this inside the event listener: </p> <p>contentEl.innerHTML = &#8220;Hi &#8221; + zname + &#8220;,nI like your braaains&#8230;&#8221;; </p> <p>CodePen Embed Fallback </p> <p>That wasn’t so bad, was it? Now we know that interactive web components are just as un-scary as the zombie dating scene… well you know what I mean. Once you get over the initial hurdle of understanding the structure of a web component, it starts to make a lot more sense. Now that you’re armed with interactive web component skills, let’s see what you can come up with! What other sorts of components or interactions would make our zombie dating service even better? Make it and share it in the comments. </p> <p>The post Interactive Web Components Are Easier Than You Think appeared first on CSS-Tricks.<br /> You can support CSS-Tricks by being an MVP Supporter.</p>

Breakdown

In my last article, we saw that web components aren’t as scary as they seem. We looked at a super simple setup and made a zombie dating service profile, complete with a custom <zombie-profile> element. We reused the element for

...