Assume I have a unique requirement to trigger a function within a custom element. The goal is to update text in the element only when a slider is moved within that specific element. Here's an example implementation in the main.js
file:
class OninputClassDemo extends HTMLElement {
constructor(){
super();
const shadow = this.attachShadow({mode:'open'});
this.parent = document.createElement('div');
this.slider = document.createElement('input');
this.slider.setAttribute('type','range');
this.slider.setAttribute('min','0');
this.slider.setAttribute('max','99');
this.slider.setAttribute('value','0')
this.text = document.createElement('input');
this.text.setAttribute('type','text');
this.text.setAttribute('value','');
this.parent.appendChild(this.slider);
this.parent.appendChild(this.text);
shadow.appendChild(this.parent);
this.slider.oninput = () => {
this.text.value = this.slider.value;
}
}
}
window.customElements.define('demo-element',OninputClassDemo);
In the HTML template:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="main.js"></script>
</head>
<body>
<demo-element></demo-element>
</body>
</html>
A common error might be:
OninputClassDemo.changeValue is not a function
at HTMLInputElement.oninput
To address this, consider updating the event listener for the slider input like so:
this.slider.oninput = WhatShouldIPutHere;
. This way, you can ensure that the text box associated with only that specific object is updated dynamically.