I have some inputs that change according to content. But seems like the script only can handle one element only. I want it can handle multiple elements
Please note that I’m going to use custom elements in future
onInput(document.getElementById('input'), "lol");
document.getElementById('input').addEventListener('input', onInput)
function onInput(i, ii) {
console.log('type')
if (ii) {
var spanElm = document.getElementById('measure');
spanElm.textContent = i.getAttribute("placeholder");
i.style.width = spanElm.offsetWidth + 'px';
} else {
var spanElm = document.getElementById('measure');
if (this.value == "") {
spanElm.textContent = this.getAttribute("placeholder");
this.style.width = spanElm.offsetWidth + 'px';
} else {
spanElm.textContent = this.value;
this.style.width = spanElm.offsetWidth + 'px';
}
}
};
<div class="input">
...
<div class="input_box">
<input type="text" placeholder="Value" id="input" />
<span id="measure"></span>
</div>
...
</div>
<div class="input">
...
<div class="input_box">
<input type="text" placeholder="Value" id="input" />
<span id="measure"></span>
</div>
...
</div>
2
Answers
I have tried this but seemed like the custom element wont work but div works
Seems like it cant detect shadowroot
First, select all the elements by using
querySelectorAll
which has the advantage of returning a Node List that can be iterated with the usage offorEach
.Then use an event delegation by adding an element parameter (you can name it as you like) to the function within the
addEventListener
.Then you can use
element.target
to reference that clicked element within the function: