In this lesson, you will learn how to create an explicit API using methods on the web component itself.
Instructor: [00:01] We'll start by creating a simple custom element. It's a class that extends HTML element. We'll add some HTML [inaudible] . We'll define the custom element on the window and use it in our HTML page. Refresh the page and see our [inaudible].
[00:21] What we'd like to do now is create an API to change the text and its color. One way to do that is to add functions to the component. I'll add the function changeTextColor() that accepts the color. As a best practice, I will save a reference to the header, and use this reference in our method to change the header's text color.
[00:45] Next I will create a changeText() method. It accepts the text and changes the header's inner text. We can refresh the page and get a reference to our custom element. We can now call the method on the element to use our new API. I'll use the changeText method to change the text to "Hello Egghead." In the same way, we can use the method to change the text color.
[01:11] To summarize, we've created a web component with some HTML. We've added two methods to the component itself. We got a reference, using querySelector(), to our custom element, and used the methods on the element to change the text and the color. You can create as many methods as you want to create more sophisticated APIs.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!