Code optimization

Asked

Viewed 70 times

1

I have a UL automatically generated via a SELECT OPTION.

In the architecture I created, I have a LABEL who gets the first OPTION of SELECT. This LABEL will also be responsible for receiving the click that will open the UL below or above it depending on your position on the page.

With the code below, I check if the LABEL is at the bottom of the visible area of the page.

If so, then position the UL on the LABEL, otherwise position the UL below the LABEL.

However, I’m finding this code much poor, with several variables, and I would like to know from you if it is possible to improve it in some way.

HTML

<div class="selectOptions">
  <select required>
    <option value="1">Um</option>
    <option value="2">Dois</option>
    <option value="3">Três</option>
    <option value="4">Quatro</option>
    <option value="5">Cinco</option>
    <option value="6">Seis</option>
    <option value="7">Sete</option>
    <option value="8">Oito</option>
  </select>
  <label class="selecionada"></label>
  <ul>
  </ul>
</div>

JQUERY

$(document).ready(function(e) {

    // entrega o primeiro elemento da select option à div .selecionada
    $(".selectOptions .selecionada").html($(".selectOptions select > option:first-child").html());

    /*popula as li's*/
    $(".selectOptions select > option").each(function() {
        //Não exibe a primeira li pois esta já está sendo exibida na .selecionada
        if ($(this).is(':first-child')) $(".selectOptions ul").append("<li value='" + this.value + "' style='display:none;'>" + this.text + "</li>");
        else $(".selectOptions ul").append("<li style='display:block;' value='" + this.value + "'>" + this.text + "</li>");
    });

    //contador de vezes que abre e fecha a ul
    contador = 0;

    $(".selectOptions .selecionada").click(function(e) {

        quantasLis = $(".selectOptions ul li").length;

        if (contador % 2 == 0) {

            $(".selectOptions .selecionada").addClass("setaCima").removeClass("setaBaixo");
            $(".selectOptions ul").css("display", "block");
            $(".selectOptions ul li").css("display", "none").slideDown(400);

            if (quantasLis > 4) {
                $(".selectOptions ul").css('height', '175px');
                $(".selectOptions ul").css("overflow-y", "scroll");
            } else {
                $(".selectOptions ul").css('height', (quantasLis*35)+'px');
                $(".selectOptions ul").css("overflow-y", "auto");
            }

            janela = $(window).height();

            selecionadaPosicao = $(".selectOptions .selecionada").offset().top;
            selecionadaAltura = $(".selectOptions .selecionada").height();
            ulAltura = $(".selectOptions ul").height();
            janelaScroll = $(window).scrollTop(); // distância que a página foi rolada

            posicaoFinal = ulAltura + $(".selectOptions .selecionada").outerHeight();

            total = selecionadaPosicao + selecionadaAltura + ulAltura - janelaScroll;

            if (total >= janela)
                $(".selectOptions ul").css("bottom", posicaoFinal, "important");
            else             
                $(".selectOptions ul").css("bottom", "0", "important");


        } else {

            $(".selectOptions .selecionada").addClass("setaBaixo").removeClass("setaCima");
            $(".selectOptions ul li").slideUp(400, function() {
                $(".selectOptions ul").css("overflow-y", "hidden");
            });
        }

        contador++;

        e.stopPropagation();

    });

    /*ai clicar na li, busca correspondência na select option e o checa (marca)*/
    $('.selectOptions ul li').on('click', function(evt) {
        /*Joga a li selecionada na label .selecionada*/
        $(".selectOptions .selecionada").html($(this).html());
        /*Joga a li selecionada ao topo da ul*/
        $($(this).closest('ul')).prepend($(this));
        // Armazena nome do maos que quer selecionar
        var li = $(this).attr("value");
        // Guarda em opcao o elemento que retornar do filtro que vai testar entre as
        // options possíveis
        var opcao = $('.selectOptions select option').filter(function() {
            // testa entre as options qual delas tem o mesmo conteúdo que o desejado
            return $(this).attr('value') === li;
        });
        // Redefine o atributo do elemento encontrado pra selecionado.
        opcao.attr('selected', true);

    });

    // ao clicar em qualquer coissa, fecha a ul caso ela esteja aberta
    $(document).on('click', function(e) {
        if (
            $(".selectOptions ul").css("overflow-y") == "auto" ||
            $(".selectOptions ul").css("overflow-y") == "scroll") {
            $(".selectOptions .selecionada").trigger("click");
        }
    });

});
  • I advise you to segment the questions more, asking one thing at a time and creating new questions.

  • Changed! @Léocunha

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.