joe,

We briefly played with web components once before on here but it has been a few years and I wanted to go a little deeper. Web components are a suite of different technologies that allow developers to create custom, reusable, encapsulated HTML tags for use in web pages and web apps. Essentially, they let you create your own HTML elements with their own functionality, independent of the rest of your codebase.

Let’s start by taking a look at a very basic example.

See the Pen by Joe Steinbring (@steinbring)
on CodePen.

In this example, the MyGreeting class extends HTMLElement to create a custom element. The constructor then creates a shadow DOM for encapsulation and adds a <span>element with a greeting message (which uses the name attribute for customization). The customElements.define method then registers the custom element with the browser, associating it with the tag <my-greeting>.

So, what can we do with this? You might have heard of Shoelace / Web Awesome. That is just a collection of cool web components. Let’s take a look at a quick example.

See the Pen by Joe Steinbring (@steinbring)
on CodePen.

As you can see above, you just include the activates Shoelace’s autoloader and then registers components on the fly as you use them. Let’s look at a slightly more complicated example.

See the Pen by Joe Steinbring (@steinbring)
on CodePen.

If you flip open the JavaScript panel, you will see that it still neeeds event listeners for the open and close buttons but it is not as complex as if you were writing this frome scratch.

https://jws.news/2024/playing-with-web-components/

  • all
  • All
  • Subscribed
  • Moderated
  • Favorites
  • javascript
  • ngwrru68w68
  • DreamBathrooms
  • khanakhh
  • magazineikmin
  • InstantRegret
  • ethstaker
  • thenastyranch
  • Youngstown
  • rosin
  • slotface
  • osvaldo12
  • everett
  • kavyap
  • Durango
  • megavids
  • cubers
  • tester
  • GTA5RPClips
  • modclub
  • mdbf
  • cisconetworking
  • tacticalgear
  • Leos
  • normalnudes
  • anitta
  • provamag3
  • JUstTest
  • lostlight
  • All magazines