Coder Social home page Coder Social logo

mdn / web-components-examples Goto Github PK

View Code? Open in Web Editor NEW
3.0K 93.0 784.0 95 KB

A series of web components examples, related to the MDN web components documentation at https://developer.mozilla.org/en-US/docs/Web/Web_Components.

License: Creative Commons Zero v1.0 Universal

HTML 41.26% JavaScript 55.06% CSS 3.68%

web-components-examples's Introduction

web-components-examples

A series of Web Components examples, related to the MDN Web Components documentation at https://developer.mozilla.org/en-US/docs/Web/API/Web_components.

Please refer to our contribution guidelines before contributing.

The following examples are available:

  • composed-composed-path. A very simple example that shows the behavior of the Event object composed and composedPath properties. See composed-composed-path live.
  • defined-pseudo-class. A very simple example that shows how the :defined pseudo-class works. See defined-pseudo-class live.
  • editable-list – <editable-list>. A simple example showing how elements can be consolidated to create a list with addable/removable items. Items are added by using a list-item attribute or by entering text and clicking the plus sign. See editable-list live.
  • edit-word<edit-word>. Wrapping one or more words in this element means that you can then click/focus the element to reveal a text input that can then be used to edit the word(s). See edit-word live.
  • element-details<element-details>. Displays a box containing an HTML element name and description. Provides an example of an autonomous custom element that gets its structure from a <template> element (that also has its own styling defined), and also contains <slot> elements populated at runtime. See element-details live.
  • expanding-list-web-component<ul is="expanding-list">. Creates an unordered list with expandable/collapsible children. Provides an example of a customized built-in element (the class inherits from HTMLUListElement rather than HTMLElement). See expanding-list live.
  • life-cycle-callbacks<custom-square l="" c="">. A trivial example web component that creates a square colored box on the page. The demo also includes buttons to create, destroy, and change attributes on the element, to demonstrate how the web components life cycle callbacks work See life-cycle-callbacks live.
  • popup-info-box-web-component<popup-info img="" text="">. Creates an info icon that when focused displays a popup info box. Provides an example of an autonomous custom element that takes information from its attributes, and defines structure and basic style in an attached shadow DOM. See popup-info-box live.
  • simple-template — A very simple trivial example that quickly demonstrates usage of the <template> and <slot> elements. See simple-template live.
  • slotchange example<summary-display>. An example that takes as its two slot values a list of possible choices, and a description for the selected choice. Multiple paragraphs are included inside the element containing all the possible descriptions; when a choice is clicked, its corresponding description paragraph is given an appropriate slot attribute so that it appears in the second slot. This example is written to demonstrate usage of the slotchange attribute, and features of the HTMLSlotElement interface See the slotchange example live.
  • slotted-pseudo-element. A very simple example that shows how the ::slotted pseudo-element works. See slotted-pseudo-element live.
  • word-count-web-component<word-count>. When added to an element, counts all the words inside that element and displays them inside an attached shadow DOM. It also contains an interval that periodically updates the word count as it changes. Provides an example of a customized built-in element (the class inherits from HTMLParagraphElement rather than HTMLElement). See word-count live.

web-components-examples's People

Contributors

arcandspark avatar b0nbon1 avatar brunoais avatar chrisdavidmills avatar darthwalsh avatar dipikabh avatar flamenco avatar hydranger avatar j8ahmed avatar janmurmann avatar knagurski avatar lisite avatar lordregenttb avatar mathiasbynens avatar maximilian5189 avatar mi4l avatar mozilla-github-standards avatar ostomachion avatar rumyra avatar wbamberg avatar webdev4422 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

web-components-examples's Issues

Inspecting attributes in custom element constructor

According to the spec for custom elements:

When authoring custom element constructors, authors are bound by the following conformance requirements:

  • ...
  • The element's attributes and children must not be inspected, as in the non-upgrade case none will be present, and relying on upgrades makes the element less usable.
  • ...

I see that the popup-info-box-web-component example calls this.hasAttribute() and this.getAttribute() in the constructor. Maybe the code can be moved to a connectedCallback method?

How to initialize a web component from JavaScript?

I'm trying to initialize the popup info box web component using JavaScript but I can't seem to make it work.
In order to have a custom image and text, I need to use the img and data-text attributes.

el = document.createElement('popup-info'); //creates the popup info box
el.setAttribute('data-text', 'Test'); //and this one doesn't have any affect
document.body.append(el);

I suppose the createElement calls the constructor, but at that moment there are no attributes yet, so it just creates a basic popup-info element with no text and default image. Is there a way to initialize such web component from JavaScript?

Word count counts itself

In the word-count-web-component example if you clear both title and body of the example, the word count will always show 2. This is because the text of the Word count is
Words: 2 which is 2 words based on that pattern /\s+/g.

The solution could be, not to count the word in the text of itself. So

 setInterval(() => {
      const count = `Words: ${countWords(wcParent)}`;
      text.textContent = count - text.textContent.split(/\s+/g).length;
    }, 200);

expanding-list-web-component err

When I switch from Google's English to Chinese;
const nextul = e.target.nextElementSibling;
The value of nextul is null and cannot be expanded.

EditableList's attribute-based approach makes for a confusing example

Taking list items as individual items is a pretty awkward API that people are using as an example of why web components have a bad API. It's a poor argument - you can make a similar component API in any framework - but there's no reason IMO to design a component this way. It would be far more ergonomic to take a list of items as a property, a JSON array as an attributes, and/or a list of child elements.

Falsy comment in the word-count-web-component javascript file.

In the word-count-web-component javascript file, there is a comment that goes as follows :

// Update count when element content changes
    setInterval(function() {
      var count = 'Words: ' + countWords(wcParent);
      text.textContent = count;
    }, 200) 

This comments proves to be falsy, because the code running under it does not apply the new word count "when" the content changes. It applies the new word count every 200 milliseconds.

To make the code reflect the comment in a more truthful way, the code should instead listen for the input event on the parent node (the article itself) since the whole article is made editable via the contenteditable attribute in the html file.

it should go like this instead :

// Update count when element content changes
this.parentNode.addEventListener('input', () => {
      var count = 'Words: ' + countWords(wcParent);
      text.textContent = count;
    });

This way, the code respects the comment more and performance is also better (even if this is a small demo, those principles should be important to always consider. Even more, since this is MDN and MDN is a reference for alot of dev coming from alot of ranges of experience)

popup-info-box-web-component violates HTML spec

The spec says this:

The element's attributes and children must not be inspected, as in the non-upgrade case none will be present, and relying on upgrades makes the element less usable.

The popup-info-box-web-component example violates this! See https://github.com/mdn/web-components-examples/blob/master/popup-info-box-web-component/main.js#L22

The example still works because the script is loaded with defer. However, it doesn't work if you do something like this:

const elem = document.createElement('popup-info');
elem.setAttribute("data-text", "foo");
document.body.appendChild(elem);

Since this example is so visible, it would be nice if it followed the spec.

getAttribute always return null

What I do

// main.js


class Test extends HTMLElement{
    constructor(){
        super()
        let shadow = this.attachShadow({mode:'open'});

        let text = this.getAttribute('text')
        if(text==null || text=="")
            text = 'null'

        let e = document.createElement("h3")
        e.textContent = text
        shadow.appendChild(e);
    }
}

window.customElements.define('my-test', Test);


<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>

    <script src="./main.js"></script>              # script line
    <my-test text="hello webcomponent"/>  # element line
  </body>
</html>

I tried ff85 and chrom88, it always print 'null' on the page.
I have read this issue #22 , it worked, but I don't understand.

  • browser parse the script line, get element name and element definition
  • browser parse the element line, get attribute.
  • find the element definition by my-test, create instance using the constructor. In the constructor, attribute should already exists. But it not.

Please tell my where i am wrong. Thank you.

Order of script and webcomponent

I was trying to use what I'd learned from these examples and not making much progress until I noticed a counter-intuitive and (as far as I can find) undocumented issue.

In https://github.com/mdn/web-components-examples/tree/master/popup-info-box-web-component for example, the code is:

    <form>
      <div>
        <label for="cvc">Enter your CVC <popup-info img="img/alt.png" data-text="Your card validation code (CVC) is an extra security feature — it is the last 3 or 4 numbers on the back of your card."></popup-info></label>
        <input type="text" id="cvc">
      </div>
    </form>

    <script src="main.js"></script>

But if you put the <script line anywhere BEFORE the <popup-info> it fails e.g.

    <script src="main.js"></script>
    <form>
      <div>
        <label for="cvc">Enter your CVC <popup-info img="img/alt.png" data-text="Your card validation code (CVC) is an extra security feature — it is the last 3 or 4 numbers on the back of your card."></popup-info></label>
        <input type="text" id="cvc">
      </div>
    </form>

Then it fails to have any attributes in popup-info and displays the default image instead.

Is this a bug, or a feature ? For pretty much anything else the normal practice is to put the script in the <head> section, but in this example putting the <script> in <head> explicitly fails.

IE is dead, Time for modern code

constructor() {
    // Always call super first in constructor
    super();

    const shadow = this.attachShadow({mode: 'open'});

    const div = document.createElement('div');
    const style = document.createElement('style');
    shadow.appendChild(style);
    shadow.appendChild(div);
  }

can be written as:

constructor() {
    super() // sets AND returns 'this' scope
       .attachShadow({mode: 'open'}) // sets AND returns this.shadowRoot
       .append(
          document.createElement('div'),
          document.createElement('style')
       );
  }

License information and file are missing

License information and file are missing .
Inclusion of these would be very useful .
Otherwise , it is not possible to use any part of example files stored in that repository outside of the Github .

Thank you very much .

Mehmet Erol Sanliturk

word-count example seems busted

I didn't see a closing </word-count> tag, but because it's a customized built-in, wouldn't it need to be <p is="word-count>?

[spam]

When I helped Mark Zuckerberg create Facebook by allowing him to open source my Copyrights of Apache 2.0 I agreed with it being free for customers of Facebook, but not companies using it as well . So there went a ton of money..I could be charging anyone and everyone for using my Copyrights and sending out invoices getting paid. Well if we can change changes to that way we can all expect a great price split

CSP

I find the examples interesting, however I can't see how you would make these work with a reasonable CSP.

I rather like the idea of having CSS contained within a shadow DOM, however all your examples appear to use inline styles. Is there a way to combine this with a CSP in a reasonable manner?

Using external CSS files for each component could easily result in dozens of network requests, so that doesn't feel like a better solution. I'm also struggling to think of anyway to use hashes without some complex tools needing to be created (and I'm trying to avoid needing a build step).

Any ideas on this? It would be nice to have a demo showing how to combine these tools.

CODE_OF_CONDUCT.md file missing

As of January 1 2019, Mozilla requires that all GitHub projects include this CODE_OF_CONDUCT.md file in the project root. The file has two parts:

  1. Required Text - All text under the headings Community Participation Guidelines and How to Report, are required, and should not be altered.
  2. Optional Text - The Project Specific Etiquette heading provides a space to speak more specifically about ways people can work effectively and inclusively together. Some examples of those can be found on the Firefox Debugger project, and Common Voice. (The optional part is commented out in the raw template file, and will not be visible until you modify and uncomment that part.)

If you have any questions about this file, or Code of Conduct policies and procedures, please see Mozilla-GitHub-Standards or email [email protected].

(Message COC001)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.