Beyond the static profile

The base <zombie-profile> element from the earlier walkthrough reuses one template across profiles and fills each one through <slot>. The obvious next step is to let users act on what they see — liking a zombie and messaging them.

Revisiting encapsulation with ::slotted()

Styles declared inside the template's <style> element stay encapsulated; styles defined outside the template do not. The ::slotted() pseudo-element narrows that gap by letting a selector target elements assigned to a slot:

::slotted(img) {
  width: 100%;
  max-width: 300px;
  height: auto;
  margin: 0 1em 0 0;
}

Any <img> placed in any slot is now matched. The limitation is that only the slotted element itself can be selected — its descendants cannot, which rules out styling children of a slot such as the interests list. Support is broadly good, but combining a pseudo-element with ::slotted, as in ::slotted(span)::after, works in some browsers (Chrome) and not others (Safari).

Animating slotted images

A fade-in with an upward translate on load sounds straightforward, and animating the image directly through img and ::slotted(img) selectors worked in Safari only. Chrome and Firefox skipped the animation for slotted images while the default image still animated. Wrapping the slot in a div with a .pic class and applying the animation to that wrapper resolved it:

.pic {
  animation: picfadein 1s 1s ease-in forwards;
  transform: translateY(20px);
  opacity: 0;
}

@keyframes picfadein {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

Likes as a checkbox

The Like control is a checkbox that triggers a heart animation when clicked. It goes at the top of the .info div:

<input type="checkbox" id="trigger"><label class="likebtn" for="trigger">Like</label>

The heart is an SVG, rendered in the eye-searing chartreuse that zombies appreciate:

<svg viewBox="0 0 160 135" class="heart" xmlns="http://www.w3.org/2000/svg" fill-rule="evenodd" clip-rule="evenodd" stroke-linejoin="round" stroke-miterlimit="2"><path d="M61 12V0H25v12H12v13H0v36h12v13h13v12h12v12h12v12h12v13h13v12h12v-12h13v-13h11V98h13V86h-1 13V74h12V61h12V25h-12V12h-12V0H98v12H85v13H74V12H61z" fill="#7aff00"/></svg>

The essential CSS added to the template's <style> element:

#trigger:checked + .likebtn {
  /* Checked state of the .likebtn. Flips the foreground/background color of the unchecked state. */
  background-color: #960B0B;
  color: #fff;
}

#trigger {
  /* With the label attached to the input with the for attribute, clicking the label checks/unchecks the box, so we can remove the checkbox. */
  display: none;
}

.heart {
  /* Start the heart off so small it's nigh invisible */
  transform: scale(0.0001);
}

@keyframes heartanim {
  /* Heart animation */
  0% { transform: scale(0.0001); }
  50% { transform: scale(1); }
  85%, 100% { transform: scale(0.4); }
}

#trigger:checked ~ .heart {
  /* Checking the checkbox initiates the animation */
  animation: 1s heartanim ease-in-out forwards;
}

None of this is web-component-specific. Because the control is really a checkbox, unliking a zombie is as simple as liking one.

Liking unlocks messaging

The messaging option should appear only after a Like, and the checkbox's checked state handles that conditionally in CSS. The markup sits directly below the heart SVG; any position works so long as it follows the #trigger element as a sibling:

<button type="button" class="messagebtn">Message</button>
#trigger:checked ~ .messagebtn {
  display: block;
}

Why the script doesn't belong in the template

Building the message form requires JavaScript. Putting a <script> element in the template creates an encapsulated script — but it also instantiates its variables once per instance, and JavaScript refuses to reconcile those indistinguishable declarations. The constructor already defined for the element is the correct home. There, a listener creates and displays a message form on click:

customElements.define('zombie-profile',
class extends HTMLElement {
  constructor() {
    super();
    let profile = document.getElementById('zprofiletemplate');
    let myprofile = profile.content;
    const shadowRoot = this.attachShadow({
      mode: 'open'
    }).appendChild(myprofile.cloneNode(true));

    // The "new" code
    // Grabbing the message button and the div wrapping the profile for later use
    let msgbtn = this.shadowRoot.querySelector('.messagebtn'),
        profileEl = this.shadowRoot.querySelector('.profile-wrapper');
    
    // Adding the event listener
    msgbtn.addEventListener('click', function (e) {

      // Creating all the elements we'll need to build our form
      let formEl = document.createElement('form'),
          subjectEl = document.createElement('input'),
          subjectlabel = document.createElement('label'),
          contentEl = document.createElement('textarea'),
          contentlabel = document.createElement('label'),
          submitEl = document.createElement('input'),
          closebtn = document.createElement('button');
        
      // Setting up the form element. The action just goes to a page I built that spits what you submitted back at you
      formEl.setAttribute('method', 'post');
      formEl.setAttribute('action', 'https://johnrhea.com/undead-form-practice.php');
      formEl.classList.add('hello');

      // Setting up a close button so we can close the message if we get shy
      closebtn.innerHTML = "x";
      closebtn.addEventListener('click', function () {
        formEl.remove();
      });

      // Setting up form fields and labels
      subjectEl.setAttribute('type', 'text');
      subjectEl.setAttribute('name', 'subj');
      subjectlabel.setAttribute('for', 'subj');
      subjectlabel.innerHTML = "Subject:";
      contentEl.setAttribute('name', 'cntnt');
      contentlabel.setAttribute('for', 'cntnt');
      contentlabel.innerHTML = "Message:";
      submitEl.setAttribute('type', 'submit');
      submitEl.setAttribute('value', 'Send Message');

      // Putting all the elments in the Form
      formEl.appendChild(closebtn);
      formEl.appendChild(subjectlabel);
      formEl.appendChild(subjectEl);
      formEl.appendChild(contentlabel);
      formEl.appendChild(contentEl);
      formEl.appendChild(submitEl);

      // Putting the form on the page
      profileEl.appendChild(formEl);
    });
  }
});

To spare users the awkward first message, prefill it with the zombie's name. The first span inside <zombie-profile> is always the name, so read it into a variable at construction time:

let zname = this.getElementsByTagName("span")[0].innerHTML;

Then insert it inside the event listener:

contentEl.innerHTML = "Hi " + zname + ",\nI like your braaains...";

An implementation whose elements can appear in a different order should target the name through a class instead of relying on position.

Upshot

Interactivity is the hard part to imagine before you build it, not the hard part to build. Once the structure of a web component is familiar, the pattern of a checkbox-driven reveal, a constructor-bound listener and a prefilled form falls into place with little ceremony.