I need to create a website that contains multiple dropdowns that have dynamic width functionality. The dropdowns are nested within large bodies of text, so it is essential that they are able to change width based on the currently selected item.
This is the script I have been working with.
<style>
:root {
--dynamic-size: 20px;
--arrow-size: 20px;
--select-size: calc(var(--dynamic-size) + var(--arrow-size));
}
.resizing-select {
width: var(--select-size);
}
.helper-element {
position: absolute;
top: 0;
left: -9999px;
}
</style>
<html>
<select id="resizing-select">
<option>All</option>
<option>books</option>
<option>audiobooks</option>
<option>Living and more</option>
</select>
<span class="helper-element" aria-hidden="true"></span>
<!-- Malfunctioning Dropdown -->
<select id="resizing-select2">
<option>All</option>
<option>books</option>
<option>audiobooks</option>
<option>Living and more</option>
</select>
<span class="helper-element" aria-hidden="true"></span>
<!-- -->
</html>
<script>
const resizingSelect = document.querySelector(".resizing-select");
const helperElement = document.querySelector(".helper-element");
resizingSelect.addEventListener("change", initResize);
function initResize(event) {
helperElement.innerHTML = event.target.querySelector(
"option:checked"
).innerText;
resize(helperElement.offsetWidth);
}
function resize(width) {
const root = document.documentElement;
root.style.setProperty("--dynamic-size", `${width}px`);
}
</script>
This what I have attempted to solve but cannot seem to figure out:
<script>
const resizingSelect = document.querySelector(".resizing-select");
const helperElement = document.querySelector(".helper-element");
resizingSelect.addEventListener("change", initResize);
function initResize(event) {
helperElement.innerHTML = event.target.querySelector(
"option:checked"
).innerText;
resize(helperElement.offsetWidth);
}
function resize(width) {
const root = document.documentElement;
root.style.setProperty("--dynamic-size", `${width}px`);
}
</script>
References:
https://codepen.io/jfaehrmann/pen/ExjpVEE
The major issue I have is that the dropdowns don’t have unique ID’s to assign individual widths. I am not confident enough in jQuery to achieve the functionality I had in mind. I have a feeling that I’m close, but I am very lost in what to do.
2
Answers
So, to make things more understandable I need to go over couple of things.
— If you do not have unique ID’s for each dropdown, you can simply use another element (Which is helper in your code) to distinguish the dropdowns.
— Once you add helpers, you can assign class (.dropdown in this case) into your select elements to trigger change method.
— The method itself simply gets the content of selected option and assigns it to its helper (the span next to it)
— Then finally, the method gets the width of span and assigns it to select box.
I hope that helps. 🙂
Here an optimized version of the previous answer