Talking to a component from JavaScript
Talk to a web component from JavaScript: set attributes and properties, call methods, listen for web component events, and wait with whenDefined().
- 01Set attributes and propertiesSay why an attribute always holds text while a property can hold any value, and choose the right one for each job.
- 02Call methods and listen for eventsCall a component's methods, listen for its exact event names, read
event.detail, and stop listening with anAbortController. - 03Wait for the definitionUse
customElements.whenDefined()before you call a method on a tag whose file may not have loaded yet.
How do you talk to a web component from JavaScript?
Ravi's menu page for Leaf and Kettle is live. He built it in the last lesson, from Web Awesome's ready-made tags, with no JavaScript at all. Now the owner wants more. Customers should rate each tea, and the page should thank them. A brewing guide should open from a script, and the page should know when it closes.
The tags work in HTML. But how does a script set them, ask them to do things, and hear back from them?
You talk to a web component the way you talk to any element. Set its attributes and properties, call its methods, and listen for its events with addEventListener(). Before you call a method, wait for the tag's class with customElements.whenDefined().
Here is the first step. A rating, and a line of text that follows it:
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-rating value="4"></wa-rating><p>You gave Green tea 4 stars.</p> <script type="module"> await customElements.whenDefined("wa-rating"); const rating = document.querySelector("wa-rating"); const note = document.querySelector("p"); rating.addEventListener("change", () => { note.textContent = `You gave Green tea ${rating.value} stars.`; });</script>- Lines 1 and 2 load Web Awesome, exactly as in lesson 2.1: the stylesheet and the loader.
- Line 4 is a
<wa-rating>: a row of five stars. Itsvalue="4"attribute lights up four of them. - Line 5 is a plain paragraph.
- Line 8 waits until the rating's class has loaded. The section on
whenDefined()explains why. - Lines 9 and 10 find the rating and the paragraph.
- Line 11 listens for
change, an event the rating fires when a customer picks a star. - Line 12 reads
rating.value, the rating's current number, and writes it into the paragraph.
Click the second star. The paragraph changes to You gave Green tea 2 stars. Three of the four ways to talk to a component are in this one example: an attribute, a property, and an event. The fourth is a method you call. This picture shows all four:
At Leaf and Kettle's counter, you can talk to the barista in a few ways. You can write your order on a slip. You can tell them a detail out loud. You can ask them to do something right now. And when your tea is ready, they call your name, and you listen for it.
- In real life: The order you write on the slip
- In JavaScript: An attribute in the HTML, like
value="4" - In real life: Telling the barista "make it large"
- In JavaScript: Setting a property, like
rating.value = 2 - In real life: Asking "can you warm it now?"
- In JavaScript: Calling a method, like
details.show() - In real life: The barista calling your name
- In JavaScript: An event, like
change, that your listener hears
A web component is an element, so you talk to it like one. Attributes and properties go in. Methods ask it to act. Events come back out to your listeners. Wait with whenDefined() until its class has loaded.
These four ways are the same tables you read in a component's docs in lesson 2.1. That lesson read them. This one uses them from a script.
What's the difference between attributes and properties?
An attribute is a setting written in the HTML, like value="4". A property is a value stored on the element object in JavaScript, like rating.value. They often share a name. They are still two different places. The Attributes and properties lesson in the JavaScript path shows this for built-in tags. Here it is on a component:
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-rating value="4"></wa-rating> <script type="module"> await customElements.whenDefined("wa-rating"); const rating = document.querySelector("wa-rating"); console.log(typeof rating.getAttribute("value")); console.log(typeof rating.value);</script>- Line 4 writes the attribute in the HTML.
- Lines 7 and 8 wait for the class, then find the rating.
- Line 9 reads the attribute with
getAttribute()and asks for its type. It printsstring. - Line 10 reads the property. It prints
number.
An attribute is always text. HTML is text, so there's nothing else it can be. The component reads that text and keeps a real number in its property. Why it matters: when you need the number, read the property.
In Leaf and Kettle's kitchen, a recipe card says "brew for 4 minutes". That's the plan, in words. The pot on the stove is what's really happening. The cook can take it off after 2 minutes, and the card still says 4. If the owner writes a new time on the card, the cook follows the new time.
- In real life: The recipe card, with words written on it
- In JavaScript: The attribute
value="4": always text - In real life: The pot on the stove right now
- In JavaScript: The property
rating.value: the current value - In real life: Taking the pot off early
- In JavaScript:
rating.value = 2: the card still says 4 - In real life: Writing a new time on the card
- In JavaScript:
setAttribute("value", 2): the cook follows it
Now try it. Pick a line, and watch the stars and the console:
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-rating value="4"></wa-rating> <script type="module"> await customElements.whenDefined("wa-rating"); const rating = document.querySelector("wa-rating"); rating.value = 2; console.log("The attribute says", rating.getAttribute("value")); console.log("The property says", rating.value);</script>Line 9 sets the property. The stars follow it, but the attribute keeps the starting value from line 4. wa-rating doesn't copy its value back into the HTML.
Two things stand out. Setting the property moved the stars but left the attribute at 4. And anything you pass to setAttribute() becomes text, even an object. A function, like the one getSymbol takes, can only go in a property.
rating.value = 2 changed only the property, so the HTML still says 4.The object case is worth seeing on its own. This code needs no page, so it runs as plain JavaScript:
const card = document.createElement("div");
const order = { tea: "Green tea", cups: 2 };
card.setAttribute("data-order", order);
console.log(card.getAttribute("data-order"));
card.order = order;
console.log(card.order.cups);- Line 1 makes a
div. Line 2 makes an order object. - Line 3 puts the object in an attribute. Line 4 prints
[object Object]. The tea and the cups are gone. - Line 5 puts the same object in a property. Line 6 prints
2. The object arrived whole.
Why it matters: lists, objects, and functions go in properties. Attributes are for short settings you could type in HTML.
Attribute names and property names
Names follow two styles. Attribute names are lowercase with hyphens, like light-dismiss. Property names use camelCase: no hyphens, and a capital letter starts each new word, like lightDismiss. The docs table shows both, the property on top. And only property names care about capital letters:
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog label="Brewing guide" light-dismiss></wa-dialog> <script type="module"> await customElements.whenDefined("wa-dialog"); const dialog = document.querySelector("wa-dialog"); console.log(dialog.lightDismiss); console.log(dialog["light-dismiss"]); dialog.setAttribute("LABEL", "How to brew"); console.log(dialog.label); console.log(dialog.Label);</script>- Line 4 turns on
light-dismissin the HTML. - Line 9 reads it as
dialog.lightDismiss. It printstrue. - Line 10 tries the attribute's name as a property. It prints
undefined. No property has that name. - Line 11 sets an attribute called
LABEL, in capitals. The browser stores it aslabel. - Line 12 prints
How to brew. Line 13 printsundefined, becauseLabelwith a capital L is a different property.
When a property copies itself into the attribute
Some properties reflect: when you set them, the component writes the attribute too. The docs mark them in a Reflects column. wa-details's open reflects. But Web Awesome writes the attribute a moment later, not on the same line:
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-details summary="How to brew green tea"> Use water at 80 degrees. Brew for 3 minutes.</wa-details> <script type="module"> await customElements.whenDefined("wa-details"); const details = document.querySelector("wa-details"); details.open = true; console.log("Right away:", details.hasAttribute("open")); await details.updateComplete; console.log("After the update:", details.hasAttribute("open"));</script>- Line 11 sets the property. The guide opens.
- Line 12 asks for the attribute at once. It prints
Right away: false. - Line 13 waits for
updateComplete, a promise every Web Awesome component has. It is ready when the component has finished its next update. - Line 14 prints
After the update: true.
Web Awesome is built with Lit, a library that saves up changes and applies them together. Its usage guide shows this same wait. Why it matters: read the attribute after updateComplete, or just read the property.
Read each row across: the question, then the answer for an attribute and for a property.
| What you want to know | An attribute | A property |
|---|---|---|
| Where do you write it? | In the HTML, like value="4", or with setAttribute(). | In JavaScript, like rating.value = 4. |
| What can it hold? | Only text. A number or an object is turned into text. | Any value: a number, an object, an array, or a function. |
| How is its name written? | In lowercase, with hyphens, like light-dismiss. Capital letters are ignored. | In camelCase, like lightDismiss. Capital letters matter. |
| Does it show in the HTML? | Yes. DevTools' Elements panel shows it. | No, unless the component copies it back into an attribute. |
| Is it there before the class loads? | Yes. The browser keeps it from the HTML. | No. The class brings it, so it reads undefined until then. |
How do you call a web component's methods?
A method is a function that belongs to the element. You call it with a dot and the call brackets, like details.show(). The Methods table in the docs lists the ones you may use. For wa-details, a box that opens to show more, it lists two: show() and hide().
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-details summary="How to brew green tea"> Use water at 80 degrees. Brew for 3 minutes.</wa-details><wa-button id="show">Show the guide</wa-button><wa-button id="hide">Hide it</wa-button> <script type="module"> const details = document.querySelector("wa-details"); document.querySelector("#show").addEventListener("click", async () => { await details.show(); console.log("The guide is open"); }); document.querySelector("#hide").addEventListener("click", () => details.hide());</script>- Lines 4 to 6 are the guide, closed. Lines 7 and 8 are two buttons.
- Line 12 runs a function when the first button is clicked.
asynclets it useawait. - Line 13 calls
show(). It opens the guide and gives back a promise. The promise is ready when the opening animation has finished.awaitwaits for it. - Line 14 prints
The guide is open, once the animation is done. - Line 16 calls
hide()when the second button is clicked.
Click Show the guide. The guide opens, and the console prints The guide is open. Click Hide it, and it closes. There is no whenDefined() here. The methods run only on a click, and by then the file has loaded.
A light switch stays up or down. Anyone can walk past and see whether the light is on. A doorbell is different. You press it, and something happens right now: someone comes to the door. You can wait at the door until they open it.
- In real life: The light switch, which stays where you put it
- In JavaScript: A property, like
details.open: you can read it back - In real life: Pressing the doorbell
- In JavaScript: A method call, like
input.focus(): it starts something now - In real life: Waiting for someone to open the door
- In JavaScript:
await details.show(): waiting until the job is done
wa-details has both. open is the switch, and show() is the doorbell. Some jobs have only a method, because no setting could do them. Moving the cursor into a box is one:
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-input label="Name for the order" value="Ravi"></wa-input><wa-button>Change the name</wa-button> <script type="module"> const input = document.querySelector("wa-input"); document.querySelector("wa-button").addEventListener("click", () => { input.focus(); input.select(); });</script>- Line 4 is a text box,
<wa-input>, that already holdsRavi. - Line 10 calls
focus(). The cursor moves into the box. - Line 11 calls
select(). The Input docs say it selects all the text.
Click Change the name, then type Asha. Your typing replaces Ravi, because it was selected.
Other components have no methods for the job at all. The Dialog docs list no method for opening. Their examples open it with a property, dialog.open = true. Why it matters: check the Methods table before you guess. Never call a method the docs don't list.
How do you listen for web component events?
An event is a message an element sends when something happens. You hear it with addEventListener(), as on any element. The first part is the event's name. Take it exactly from the component's Events table. For wa-dialog, the table lists wa-show, wa-after-show, wa-hide, and wa-after-hide.
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog id="guide" label="Brewing guide"> Use water at 80 degrees. Brew for 3 minutes. <wa-button slot="footer" data-dialog="close">Close</wa-button></wa-dialog><wa-button data-dialog="open guide">Brewing guide</wa-button> <script type="module"> const dialog = document.querySelector("wa-dialog"); dialog.addEventListener("wa-show", () => console.log("The guide opened")); dialog.addEventListener("wa-hide", (event) => { console.log("Closed by", event.detail.source.localName); });</script>- Lines 4 to 7 are the guide, a
wa-dialog, with a Close button in its footer. - Line 8 opens it, with the
data-dialogattribute from lesson 2.1. - Line 12 listens for
wa-showand printsThe guide opened. - Line 13 listens for
wa-hide. Its function gets the event object, here calledevent. - Line 14 reads
event.detail.source: the element that closed the guide. It prints that element's tag name.
Open the guide, and the console prints The guide opened. Press Close, and it prints Closed by wa-button. Open it again and press the Escape key. Now it prints Closed by dialog. The source is the browser's own <dialog> element, inside the component. The docs say this source means the Escape key or your own code closed it.
At a busy café, you order and get a small buzzer. You don't stand at the counter asking "Is it ready?". You sit down. When your tea is ready, the buzzer buzzes, and its screen shows your order number.
- In real life: Taking a buzzer
- In JavaScript:
addEventListener("wa-hide", …) - In real life: The buzz
- In JavaScript: The event, fired by the component
- In real life: The number on its screen
- In JavaScript:
event.detail, the data the event carries - In real life: A buzzer that works only once
- In JavaScript: The
once: trueoption - In real life: Handing all your buzzers back
- In JavaScript:
controller.abort()
The name must match exactly
A listener with the wrong name never runs, and nothing tells you. Try five names on the same page:
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog id="guide" label="Brewing guide"> Use water at 80 degrees. <wa-button slot="footer" data-dialog="close">Close</wa-button></wa-dialog><wa-button data-dialog="open guide">Brewing guide</wa-button> <script type="module"> const dialog = document.querySelector("wa-dialog"); dialog.addEventListener("wa-hide", () => console.log("Heard it"));</script>wa-hide is the name in the Dialog docs' Events table. Close the guide, and the console prints Heard it.
Only wa-hide works. Web Awesome puts wa- in front of its own events. Names care about capital letters, as MDN says. And Shoelace's old sl- names are gone. Why it matters: copy the name from the Events table, letter for letter.
Where an event keeps its data
A component can send its own events as a CustomEvent. The DOM standard gives it one extra property, detail, for any data the event carries. The Custom events lesson shows how one is made. Web Awesome's events have their own classes, like WaHideEvent. They put their data in detail too. So event.detail.source works on wa-hide, and event.detail.value works on the rating's wa-hover. An event with no data, like the rating's change, has no detail. Read rating.value instead, as line 12 of the first example does.
Listening once, and stopping later
addEventListener() takes a third part: an object of options. Two of them help on a component's page.
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog id="guide" label="Brewing guide">Use water at 80 degrees.</wa-dialog><wa-button data-dialog="open guide">Brewing guide</wa-button><wa-button id="stop">Stop listening</wa-button> <script type="module"> const dialog = document.querySelector("wa-dialog"); const controller = new AbortController(); dialog.addEventListener("wa-show", () => console.log("Welcome!"), { once: true }); dialog.addEventListener("wa-show", () => console.log("Opened"), { signal: controller.signal }); dialog.addEventListener("wa-hide", () => console.log("Closed"), { signal: controller.signal }); document.querySelector("#stop").addEventListener("click", () => controller.abort());</script>- Line 10 makes an
AbortController: an object with one job, to send a stop signal when you call itsabort()method. - Line 11 adds
once: true. The browser removes this listener after it runs one time. - Lines 12 and 13 pass
signal: controller.signal. Each listener is tied to the controller. - Line 14 calls
controller.abort()on a click. The browser removes both tied listeners at once.
Open and close the guide. The console prints Welcome!, Opened, and Closed. Do it again: only Opened and Closed. Click Stop listening, and the next open and close print nothing. Why it matters: one abort() call removes many listeners, so you don't have to keep every function to remove it later. The Cancellation with AbortController lesson uses the same object to stop requests.
Do web component events cross the shadow DOM?
Some do, and some don't. It depends on two settings each event is made with:
bubbles: when it'strue, the event travels up through the element's parents, as Bubbling and capturing showed. It's like a message passed from a table, to the counter, to the manager.composed: when it'strue, the event can leave the shadow root it started in. A shadow root is a component's private tree, from lesson 1.1.
Both start as false, the DOM standard says. Web Awesome makes wa-show and wa-hide with both set to true. So you don't have to listen on each element. One listener on the whole page hears them all:
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-details summary="Green tea">Brew for 3 minutes.</wa-details><wa-details summary="Black tea">Brew for 4 minutes.</wa-details> <script type="module"> document.addEventListener("wa-show", (event) => { console.log("Opened:", event.target.summary); });</script>- Lines 4 and 5 are two guides, one for each tea.
- Line 8 listens on
document, the top of the page. - Line 9 reads
event.target, the element the event came from. It prints itssummary, the guide's title.
Open the green tea guide, then the black tea one. The console prints Opened: Green tea, then Opened: Black tea. This is event delegation, and it works because the event bubbles.
wa-hide on the wa-dialog element itself, and it bubbles up to the body and the document. The inner <dialog>'s close event never leaves the shadow root.The picture shows why close failed in the playground. wa-dialog has a browser <dialog> inside its shadow root. That <dialog> fires close, but close doesn't bubble and isn't composed. It never leaves the shadow root. Web Awesome fires wa-hide on the outer element, where your page can hear it.
From inside another shadow root
composed matters most when the library's tag sits inside another component. Here a wa-details lives in the shadow root of <tea-guide>, like the button inside tea-order in lesson 2.1:
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/components/details/details.js"></script> <tea-guide></tea-guide> <script> class TeaGuide extends HTMLElement { constructor() { super(); const shadow = this.attachShadow({ mode: "open" }); shadow.innerHTML = '<wa-details summary="How to brew">Brew for 3 minutes.</wa-details>'; } } customElements.define("tea-guide", TeaGuide); document.addEventListener("wa-show", (event) => { console.log("Opened, says", event.target.localName); });</script>- Line 2 loads the details file directly. The autoloader can't see inside a shadow root, as lesson 2.1 showed.
- Lines 7 to 14 define
tea-guide. Line 11 puts awa-detailsin its shadow root. - Line 16 listens on
document. Line 17 prints the target's tag name.
Open the guide. The console prints Opened, says tea-guide. The event crossed out of the shadow root, because it's composed. Outside, the browser shows the host, tea-guide, as the target, and keeps the inside private. This is called retargeting. The lesson on event retargeting follows the whole path.
Read each row across: the event, then whether it bubbles, then whether it leaves a shadow root.
| Which event | Does it bubble? | Does it leave a shadow root? |
|---|---|---|
wa-show and wa-hide, from wa-dialog and wa-details | Yes. A listener on the document hears it. | Yes. It's composed. |
wa-hover, from wa-rating | Yes. A listener on the document hears it. | Yes. It's composed. |
change, from wa-rating | Yes. A listener on the document hears it. | Yes. It's composed. |
close, from the <dialog> inside wa-dialog | No. It doesn't travel up through the parents. | No. It stays inside the component. |
Why it matters: if a listener on a parent never runs, check whether the event bubbles. Or listen on the component itself.
What does customElements.whenDefined() do?
Ravi wants the brewing guide to open as soon as the page loads. He moves details.show() to the top of his script. The console shows an error, and the guide stays shut. What went wrong?
Timing. The autoloader is a module script. It runs after the HTML has been read, and then it starts loading each component's file. Ravi's script runs before those files arrive. At that moment, <wa-details> is a tag the browser doesn't know yet, as in lesson 1.1. It's a plain HTML element, with no show(). Try three ways to start:
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-details summary="How to brew green tea"> Use water at 80 degrees. Brew for 3 minutes.</wa-details> <script type="module"> const details = document.querySelector("wa-details"); console.log("Defined yet?", customElements.get("wa-details") !== undefined); // No waiting details.show();</script>Line 10 prints Defined yet? false: the file for wa-details hasn't arrived. Until it does, the tag is a plain HTML element with no show() method. So line 12 throws a TypeError, and the guide stays closed.
Calling the method too early throws TypeError: details.show is not a function. Waiting fixes it. customElements.whenDefined("wa-details") gives back a promise. The promise is ready once wa-details is defined and every one on the page is upgraded. await pauses the script until then.
wa-details is a tag with no class, so show() throws. When its file loads, define() upgrades it, and the promise from whenDefined() resolves. Code after the await runs from there.Ravi wants a teapot the shop doesn't have yet. He leaves his number and asks them to call when it comes in. He doesn't phone every hour. If it's already on the shelf, they tell him straight away.
- In real life: The teapot that hasn't arrived
- In JavaScript: The class for
wa-details, still loading - In real life: Leaving your number
- In JavaScript:
customElements.whenDefined("wa-details") - In real life: The call that says "it's here"
- In JavaScript: The promise fulfills, with the class
- In real life: A teapot already on the shelf
- In JavaScript: A tag that's already defined: the promise is ready at once
What the promise gives you
The promise fulfills with the class itself:
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-rating value="4"></wa-rating> <script type="module"> const Rating = await customElements.whenDefined("wa-rating"); console.log(Rating.name); console.log(Rating === customElements.get("wa-rating")); console.log(document.querySelector("wa-rating") instanceof Rating);</script>- Line 7 waits for
wa-ratingand keeps what the promise gives inRating. - Line 8 prints the class's name,
WaRating. - Line 9 prints
true: it's the classcustomElements.get()returns. - Line 10 prints
true: the rating on the page is now built from that class.
Two mistakes behave very differently. A name with no hyphen isn't a valid custom element name. Then the promise fails at once with a SyntaxError:
<script type="module"> try { await customElements.whenDefined("rating"); } catch (error) { console.log(error.name); }</script>Line 3 asks for rating, with no hyphen. Line 5 prints SyntaxError. But a valid name that is spelled wrong, like wa-ratng, fails silently. Nothing ever defines it, so the promise waits forever, with no error. Why it matters: when code after an await never runs, check the spelling of the tag.
Properties set too early
In the playground, setting open early worked. Web Awesome is built with Lit, and Lit keeps a property you set before the upgrade, then hands it to the class. A component written by hand may not. Here is a small version of tea-price with an amount property and nothing else:
<p>Green tea. <tea-price></tea-price></p> <script> const price = document.querySelector("tea-price"); price.amount = 4;</script><script type="module" src="tea-price.js"></script>- Line 1 puts
<tea-price>in a paragraph. - Line 5 sets
amountin a classic script, which runs at once. - Line 7 loads the class. A module script runs later, after the HTML is read.
- In the
tea-price.jstab, lines 2 to 4 are a setter: a function that runs when someone setsamount. It writesPrice: 4.
The result shows Green tea. and no price. Line 5 ran first, on a plain element, so it made an ordinary property called amount. That property now sits in front of the class's setter, which never runs. Set it after await customElements.whenDefined("tea-price"), and the result shows Green tea. Price: 4. Stage 2 shows component authors how to guard against this.
Why it matters: before a component's class arrives, its methods are missing, and its properties may not stick. Wait with whenDefined() whenever your code runs as the page loads.
Open a brewing guide from JavaScript
Ravi now has everything the owner asked for. First, sort each job by the way you'd do it:
- Show 4 stars when the page first loads
- Close the guide when someone clicks outside it
- Give the rating a function that draws dots
- Open the guide from a click handler
- Open the details and wait until it has finished opening
- Put the cursor in the name box
- Know when the guide closes
- Know which star the pointer is on
Sort each job on Ravi's menu page by the way you'd talk to the component.
Here is his menu card. It has a rating and a button that opens the guide. The page logs what happens, and one button stops all the logging:
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-card> <strong slot="header">Green tea</strong> Brew for 3 minutes. Price: 4 <wa-rating label="Rate green tea" value="4"></wa-rating> <wa-button slot="footer" id="open-guide">Brewing guide</wa-button> <wa-button slot="footer" id="stop">Stop logging</wa-button></wa-card> <wa-dialog id="guide" label="Brewing guide"> Use water at 80 degrees. Brew for 3 minutes. <wa-button slot="footer" data-dialog="close">Close</wa-button></wa-dialog> <script type="module"> const rating = document.querySelector("wa-rating"); const dialog = document.querySelector("#guide"); const controller = new AbortController(); const { signal } = controller; document.querySelector("#open-guide").addEventListener("click", () => { dialog.open = true; }); rating.addEventListener("change", () => console.log("Rated", rating.value), { signal }); dialog.addEventListener("wa-show", () => console.log("Guide opened"), { signal }); dialog.addEventListener("wa-hide", (event) => { console.log("Guide closed by", event.detail.source.localName); }, { signal }); document.querySelector("#stop").addEventListener("click", () => controller.abort());</script>- Lines 4 to 10 are a card. Line 7 is the rating. Lines 8 and 9 are two buttons in the card's footer.
- Lines 12 to 15 are the guide.
- Lines 20 and 21 make one
AbortControllerand take itssignalout into a variable of its own. - Lines 23 to 25 open the guide on a click, with the
openproperty. - Lines 26 to 30 add three listeners: the rating's
change, thenwa-showandwa-hide. Each one is tied to the same signal. - Line 31 calls
abort()when Stop logging is clicked.
Click the fifth star. The console prints Rated 5. Open the guide and press Close: Guide opened, then Guide closed by wa-button. Now click Stop logging. The stars and the guide still work, but the console stays quiet. One call removed all three listeners.
This script has no whenDefined(), and it doesn't need one. addEventListener() works on any element, defined or not. And the only property it sets is set on a click.
Common mix-ups
- "An attribute and a property with the same name are the same thing." No. The attribute is text in the HTML, and the property is a value on the element. Setting
rating.valueleft the attribute at4. - "You can pass an object or a list through an attribute." No. It becomes the text
[object Object]. Use a property. - "After you set a property, the attribute changes on the next line." No. Web Awesome writes reflected attributes a moment later. Wait for
updateComplete. - "A listener for
hidehearswa-hide." No. The name must match exactly, prefix and capital letters included. - "Every event inside a component reaches the page." No. Only composed events leave a shadow root. The inner
<dialog>'sclosenever does. - "The browser waits for a component's class before running your script." No. Your script can run first. Wait with
customElements.whenDefined(). - "
whenDefined()tells you when a tag name is wrong." No. Only a name with no hyphen fails. A misspelled valid name waits forever.
Practice exercises
Answer first, then use the hints. Every result runs live, so you can check yourself.
What does line 10 print?
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-rating value="3"></wa-rating> <script type="module"> await customElements.whenDefined("wa-rating"); const rating = document.querySelector("wa-rating"); rating.value = 5; console.log(rating.getAttribute("value"));</script>It prints 3. rating.value = 5 changes only the property, and five stars light up. The value attribute keeps the starting value from line 4.
Open and close the guide. Nothing prints. Which name should line 12 listen for?
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog id="guide" label="Brewing guide"> Use water at 80 degrees. <wa-button slot="footer" data-dialog="close">Close</wa-button></wa-dialog><wa-button data-dialog="open guide">Brewing guide</wa-button> <script type="module"> const dialog = document.querySelector("wa-dialog"); dialog.addEventListener("hide", () => console.log("Heard it"));</script><link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog id="guide" label="Brewing guide"> Use water at 80 degrees. <wa-button slot="footer" data-dialog="close">Close</wa-button></wa-dialog><wa-button data-dialog="open guide">Brewing guide</wa-button> <script type="module"> const dialog = document.querySelector("wa-dialog"); dialog.addEventListener("wa-hide", () => console.log("Heard it"));</script>wa-hide. Nothing fires hide. With the name from the Events table, closing the guide prints Heard it.
Replace the comment on line 10 so the button opens the guide. Which property did you set?
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog id="guide" label="Brewing guide">Use water at 80 degrees.</wa-dialog><wa-button>Brewing guide</wa-button> <script type="module"> const dialog = document.querySelector("wa-dialog"); document.querySelector("wa-button").addEventListener("click", () => { // Open the dialog here });</script><link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog id="guide" label="Brewing guide">Use water at 80 degrees.</wa-dialog><wa-button>Brewing guide</wa-button> <script type="module"> const dialog = document.querySelector("wa-dialog"); document.querySelector("wa-button").addEventListener("click", () => { dialog.open = true; });</script>dialog.open = true. The open property opens the dialog, and the dialog fires wa-show as it does.
Point at a star. The paragraph says undefined. Fix line 11. Where does the hovered value live?
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-rating value="4"></wa-rating><p>Point at a star.</p> <script type="module"> const rating = document.querySelector("wa-rating"); const note = document.querySelector("p"); rating.addEventListener("wa-hover", (event) => { note.textContent = `You're pointing at ${event.value} of 5.`; });</script><link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-rating value="4"></wa-rating><p>Point at a star.</p> <script type="module"> const rating = document.querySelector("wa-rating"); const note = document.querySelector("p"); rating.addEventListener("wa-hover", (event) => { note.textContent = `You're pointing at ${event.detail.value} of 5.`; });</script>In event.detail. Line 11 needs event.detail.value. Point at the third star, and the paragraph says You're pointing at 3 of 5.
Ravi wants the total of all the stars. The console prints Total stars: NaN. Fix it. What does it print once fixed?
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-rating value="4"></wa-rating><wa-rating value="5"></wa-rating><wa-rating value="3"></wa-rating> <script type="module"> let total = 0; for (const rating of document.querySelectorAll("wa-rating")) { total += rating.value; } console.log("Total stars:", total);</script><link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-rating value="4"></wa-rating><wa-rating value="5"></wa-rating><wa-rating value="3"></wa-rating> <script type="module"> await customElements.whenDefined("wa-rating"); let total = 0; for (const rating of document.querySelectorAll("wa-rating")) { total += rating.value; } console.log("Total stars:", total);</script>12. Before the class arrives, rating.value is undefined, and adding undefined gives NaN. After await customElements.whenDefined("wa-rating"), each value is a number: 4, 5, and 3. Reading Number(rating.getAttribute("value")) would also work, because attributes are there from the HTML.
Make Stop logging remove all three listeners with one call. Which call is it?
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog id="guide" label="Brewing guide">Use water at 80 degrees.</wa-dialog><wa-button data-dialog="open guide">Brewing guide</wa-button><wa-button id="stop">Stop logging</wa-button> <script type="module"> const dialog = document.querySelector("wa-dialog"); dialog.addEventListener("wa-show", () => console.log("Opening")); dialog.addEventListener("wa-after-show", () => console.log("Open")); dialog.addEventListener("wa-hide", () => console.log("Closing")); document.querySelector("#stop").addEventListener("click", () => { // Stop all three listeners here });</script><link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog id="guide" label="Brewing guide">Use water at 80 degrees.</wa-dialog><wa-button data-dialog="open guide">Brewing guide</wa-button><wa-button id="stop">Stop logging</wa-button> <script type="module"> const dialog = document.querySelector("wa-dialog"); const controller = new AbortController(); const { signal } = controller; dialog.addEventListener("wa-show", () => console.log("Opening"), { signal }); dialog.addEventListener("wa-after-show", () => console.log("Open"), { signal }); dialog.addEventListener("wa-hide", () => console.log("Closing"), { signal }); document.querySelector("#stop").addEventListener("click", () => { controller.abort(); });</script>controller.abort(). Every listener added with { signal } is removed when its controller aborts. After Stop logging, opening and closing the guide prints nothing.
Check your understanding
For each question, ask which way the message goes: in through an attribute, property, or method, or out as an event.
Question 1 of 8A page has
<wa-rating value="4">. What doesrating.getAttribute("value")give back?Choose an answer to see the explanation.
Question 2 of 8What does line 4 of this code print?
Read the code, then predictconst card = document.createElement("div"); const order = { tea: "Green tea", cups: 2 }; card.setAttribute("data-order", order); console.log(card.getAttribute("data-order")); card.order = order; console.log(card.order.cups);Choose an answer to see the explanation.
Question 3 of 8In the HTML, the dialog's attribute is
light-dismiss. Which line turns it on from JavaScript?Choose an answer to see the explanation.
Question 4 of 8You open this guide, close it, and open it again. What does the console print?
Read the code, then predict<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"> <script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog id="guide" label="Brewing guide">Use water at 80 degrees.</wa-dialog> <wa-button data-dialog="open guide">Brewing guide</wa-button> <script type="module"> const dialog = document.querySelector("wa-dialog"); dialog.addEventListener("wa-show", () => console.log("A"), { once: true }); dialog.addEventListener("wa-show", () => console.log("B")); </script>Choose an answer to see the explanation.
Question 5 of 8A page listens for
closeon awa-dialog, and the listener never runs. Why?Choose an answer to see the explanation.
Question 6 of 8What does
await customElements.whenDefined("wa-rating")give back?Choose an answer to see the explanation.
Question 7 of 8A script runs before Web Awesome's files arrive and calls
details.show(). What happens?Choose an answer to see the explanation.
Question 8 of 8A listener on
documenthearswa-showfrom awa-detailsinside<tea-guide>'s shadow root. What isevent.target?Choose an answer to see the explanation.
Key takeaways
- You talk to a web component like any element: attributes, properties, methods, and events.
- An attribute is always text in the HTML. A property is any value on the element. Objects, lists, and functions go in properties.
- Attribute names are lowercase with hyphens, like
light-dismiss. Property names are camelCase, likelightDismiss. - Call only the methods the docs list. Some, like
details.show(), give back a promise you can await. - Listen for the exact event name, like
wa-hide. Data lives inevent.detail. Useonceand anAbortControllerto stop listening. - Events that bubble and are composed reach the whole page. Outside a shadow root, the target is the host.
- Before a class arrives, methods are missing.
await customElements.whenDefined()waits, and gives you the class.
Remember the one-liner.
Settings go in as attributes and properties, requests as method calls, and news comes out as events, once the class has arrived.
Sources
The facts on this page come from these docs, specifications, and posts:
- Usage: attributes, events, methods, and waiting for components, Web Awesome.
- Rating, Web Awesome.
- Attribute reflection, MDN.
- HTML attributes vs DOM properties, Jake Archibald.
- Details, Web Awesome.
- Input, Web Awesome.
- Dialog, Web Awesome.
- EventTarget: addEventListener(), MDN.
- Interface CustomEvent, DOM Standard, WHATWG.
- AbortController, MDN.
- Event: composed, MDN.
- Interface Event, DOM Standard, WHATWG.
- CustomElementRegistry: whenDefined(), MDN.
- Custom elements: whenDefined(), HTML Standard, WHATWG.
- Handling properties in custom element upgrades, Nolan Lawson.
- Custom element best practices, web.dev.
Coming next: Theming components from the outside. Change a component's colors, sizes, and fonts with custom properties and CSS parts.