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