liveBook · Manning

Event

As explained in Web Components in Action

A change event is a browser-dispatched DOM event indicating that the value of a form control has changed.

A change event is a native DOM event: the browser dispatches it when a form control’s value changes. A handler can use the event to find the selected value and update another element. section 14.2 section 7.3

Choose a layout

A select menu calls updateLayout(event) on change. The handler reads event.target.value and passes it to setAttribute('layout', ...). The custom element then responds through attributeChangedCallback, replacing its displayed template with the chosen layout. section 7.3

Listing 7.8. Setting the layout attribute from a menu outside of our component
<body>
   <p>
       <select onchange="updateLayout(event)">                        #1
           <option value="none">none</option>
           <option value="default-card">default</option>
           <option value="variation">variation</option>
       </select>
   </p>
   <biz-card layout="none"></biz-card>

   <script>
       function updateLayout(event) {
           document.querySelector('biz-card').setAttribute('layout',
           event.target.value);                                     #2
       }
   </script>
</body>

See the menu and handler together: the event supplies the selected value, while setAttribute passes it to the custom element. section 7.3

Need a component to announce a change of its own? That is a separate choice: JavaScript can create and dispatch a CustomEvent for other code to hear. The select menu’s change event is instead generated by the browser. section 14.2

How Web Components in Action covers it

How deep it goes
Defines native events as browser-generated and works through one change handler, without detailing change-event timing.
Examples
Shows a select menu choosing among business-card templates by passing event.target.value to setAttribute.
What it assumes
Assumes familiarity with browser events and teaches their use with a select menu rather than introducing event handling from zero.
What you can do after
Apply it via DOM event handlers to update a custom element’s attribute from a select menu.
How it connects
Links change events to DOM event handling, custom elements, observed attributes, and attributeChangedCallback.

Also explained in

Compare how 18 books explain event →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.