Cartoon Network Logo with Web Component
December 22, 2024

Cartoon Network Logo with Web Component

I’ve loved the classic Cartoon Network logo since I was a kid.

I created a custom HTML element to make the text a different color.

class CartoonNetworkify extends HTMLElement {

    // respond to color updates
    static observedAttributes = ['color1','color2'];

    constructor() {
        super();
    }

    connectedCallback() {
            let words = this.innerText.split(' ');
        this.attachShadow({mode:'open'});
        var root = this.shadowRoot;
        var table = document.createElement('table');

        // longest word length
        let maxLength = words.reduce((max,w, i)=>  w.length > max ? w.length: max, Number.MIN_VALUE);

        // default black & white
        var color1 = this.getAttribute('color1') || 'black';
        var color2 = this.getAttribute('color2') || 'white';

        words.reduce((tbody,line,i,words)=>{
            // pad for extra space
            line = line.padEnd(maxLength);
            let trow = line.split('').reduce((trow,letter,j)=>{
                // create cells
                let td = trow.insertCell();
                td.innerText = letter.toUpperCase();
                let odd  = i%2 == j%2;
                td.dataset.odd = odd;

                                td.style.backgroundColor=odd?color1:color2;
                    td.style.color = odd?color2:color1;
                return trow;
                    }, tbody.insertRow());
                    return tbody;
                }, table.createTBody());
                root.append(table);

                // add style from template
                let template = document.getElementById('cartoon-networkify-template');
                root.append(template.content.cloneNode(true));
            }

            // update attributes later
            attributeChangedCallback(name,oldValue, newValue) {             
                if(this.shadowRoot) {
                    this.shadowRoot.querySelectorAll('td').forEach((td)=> {
                        var odd = td.dataset.odd == 'true';
                        if(name=='color1') {
                            td.style[odd?'backgroundColor':'color'] = newValue  ;
                        } else if(name == 'color2') {
                            td.style[odd?'color':'backgroundColor'] = newValue  ;
                        }
                    });
                }
            }

        }

Enter full screen mode

Exit full screen mode

If you have any questions, please feel free to ask me.

To learn more about custom elements, visit MDN.

2024-12-22 20:06:28

Leave a Reply

Your email address will not be published. Required fields are marked *