Simple Barcode-Viewer

Hi everyone

This is a simple barcode-viewer, which even works in repeaters!

Custom Element Code:

class BarcodeWidget extends HTMLElement {
    constructor() {
        super();
        const barcodeScript = document.createElement("script");
        barcodeScript.src = "https://cdn.jsdelivr.net/npm/jsbarcode@3.11.5/dist/JsBarcode.all.min.js";
        barcodeScript.onload = () => {
            this.isJsBarcodeLoaded = true;
            this.maybeUpdateBarcode();
        };
        document.head.appendChild(barcodeScript);
        this.innerHTML = `<svg id="barcode"></svg>`;
    }

    connectedCallback() {
        this.maybeUpdateBarcode();
    }

    attributeChangedCallback(name, oldValue, newValue) {
        if (name === 'data-barcode') {
            this.maybeUpdateBarcode();
        }
    }

    maybeUpdateBarcode() {
        if (this.isJsBarcodeLoaded && this.getAttribute('data-barcode')) {
            const barcodeSVG = this.querySelector('#barcode');
            barcodeSVG.setAttribute('width', '100%');
            barcodeSVG.setAttribute('height', '100%');
            if (barcodeSVG) {
                JsBarcode(barcodeSVG, this.getAttribute('data-barcode'), {
                    format: "EAN13",
                    lineColor: "#000",
                    width: 1,
                    height: 50,
                    displayValue: true
                });
            }
        }
    }

    static get observedAttributes() {
        return ['data-barcode'];
    }
}

customElements.define('barcode-widget', BarcodeWidget);

Frontend Code:

        $w("#repeater1").forEachItem(($item, itemData, index) => {
            $item("#barcode").setAttribute('data-barcode', itemData.barcode);
        });

This uses the setAttribute method for passing an EAN13 Code to the custom element, which then displays it nicely. Btw. it should also work for all different kinds of Barcodes, just replace the according value in the custom element code. (Also you can change the colors of the bars, etc.)

Hope this helps someone :slight_smile:

1 Like

Quick Update for this:

In the meantime I tried to optimize it and found a Google Font which you can implement on your site to view Barcodes. This way you don’t need the custom element and performance is improved.

→ Just install this font on your Site:

Of course this also works in repeaters, etc.

1 Like