Kopper
Kopper

Reputation: 123

html empty select resizes when an element is added

I have an empty select component with a fixed width that has options added to it by Javascript. It uses a scrollbar by default. When the page loads, this element isn't quite the right height. When an option is added, the select element resizes to the correct height and stays that way until the page is reloaded or the list of options cleared. Is there a way I can make the selector load at the correct height without initializing it with an option?

function addOpt() {
  let selector = document.getElementById("selector");
  let opt = document.createElement("option");
  opt.innerHTML = "New option";
  selector.appendChild(opt);
}
<select size="8" style="width: 250px;" id="selector">
</select>
<br /><br />
<button type="button" onclick="addOpt()">Click me</button>

Upvotes: 2

Views: 47

Answers (1)

Victor
Victor

Reputation: 2371

Try this:

<!DOCTYPE html>
<html lang="es">
<head>
    <script type="text/javascript">
        function getSelectHeight(rowsCount) {
            var rowsHtml = '';
            for (var i = 0; i < rowsCount; i++)
                rowsHtml += '<option>.</option>';

            var div = document.createElement('div');
            div.innerHTML = '<select size="' + rowsCount + '" style="width: 250px;visibility:hidden">' + rowsHtml + '</select>';
            document.body.after(div);

            var height = div.offsetHeight;
            div.remove();
            return height;
        }

        function setSelectorHeight() {
            var select = document.getElementById('selector');
            var rowsCount = select.getAttribute('size');
            select.style.height = getSelectHeight(rowsCount) + 'px';
        }

        function addOpt() {

            let selector = document.getElementById("selector");
            let opt = document.createElement("option");
            opt.innerHTML = "New option";
            selector.appendChild(opt);
        }
    </script>
</head>
<body onload="setSelectorHeight()">

    <select size="8" style="width: 250px" id="selector"></select>

    <button type="button" onclick="addOpt()">Click me</button>

</body>
</html>

getSelectHeight give us the real height of the selector with the specified rowsCount. Here we add a non visible selector with rowsCount items, get the real height of it and remove the selector.

On body onload we run setSelectorHeight: find our selector, check the number of rows (size attribute) and set the height of the selector. I use the style because setting offsetHeight doesn't work.

Upvotes: 1

Related Questions