skip to Main Content

How can I create a custom HTML element that can be styled with CSS and have specific behaviors, such as click events, proper semantics, and accessibility? Are there any best practices for defining specific behaviors for custom HTML elements using event listeners? What are some examples of custom HTML elements that have been successfully implemented on websites

<!DOCTYPE html>
<html>
<head>
    <title>Custom HTML Element Example</title>
    <style>
        .custom-element {
            background-color: #ccc;
            padding: 10px;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <custom-element >Click me</custom-element>

    <script>
        class CustomElement extends HTMLElement {
            constructor() {
                super();
                this.addEventListener('click', () => {
                    alert('You clicked the custom element!');
                });
            }
        }

        window.customElements.define('custom-element', CustomElement);
    </script>
</body>
</html>

element is not keyboard accessible

2

Answers


  1. Have you tried tabindex property?

    You should set that at

    <custom-element >Click me</custom-element>
    

    Like:

    <custom-element tabindex="0">Click me</custom-element>
    

    If you define a custom element, you should think that as a re usable, agnostic element, and that can be customizable, so, you can pass data and also add event listener as any other html element

    Login or Signup to reply.
  2. FYI: Your click only works here because you defined the component after <custom-element> was parsed in the DOM. By default there is no DOM created in the constructor (try a document.createElement("custom-element"); it will error.

    The connectedCallback tells you when the element is actually in the DOM, and that is when you can assign Events.

    <style>
      .custom-element {
        background-color: #ccc;
        padding: 10px;
        cursor: pointer;
      }
    </style>
    </head>
    
    <body>
      <custom-element>Click me</custom-element>
    
      <script>
        customElements.define('custom-element', class extends HTMLElement {
          //constructor() {
            //super();
            // only set properties or shadowDOM here
            // this element is NOT in the DOM yet!
          //}
          connectedCallback(){
            // might as well do oldskool inline clicks here
            // because (in principle) no other code in the page
            // should mess with this component
            this.onclick = () => alert("inline click!");
    
            this.addEventListener('click', () => {
              alert('You clicked the custom element!');
            });
          }
        });
      </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search