Set background color in DIV when sort alphabetically in jQuery

Asked

Viewed 114 times

1

Good night!

I’m trying to put together a list as follows:

<div>
  <div>id</div>
  <div><a id="orderStatus">status</a></div>
</div>
<div id="container">
  <div class="listStatus" style="background-color:#fff">
    <div>C</div>
    <div>1</div>
  </div>
  <div>
    <div class="listStatus" style="background-color:#DCDCDC">C</div>
    <div>2</div>
  </div>
  <div>
    <div class="listStatus" style="background-color:#FFF">A</div>
    <div>3</div>
  </div>
  <input type="hidden" id="acao" value="asc" />
</div>

The format that is printed is the same as a table, but with div’s.

To facilitate the visualization of the line, I created a line with background FFF and the other DCDCDC and so on, getting 'color yes, color no', but when I sort, the colors sort together making the color functionality lose the goal, which is to facilitate viewing.

Is there any way to make color correction in the function below?

    $("#orderStatus").click(function(){
        var acao = $('#acao').val();
        var statusList = $(".listStatus");
        statusList.sort(function(a, b) {
            if(acao == "asc"){
                $('#acao').val('desc');
                var res = $(b).attr("status") > $(a).attr("status");
            }
            else{
                $('#acao').val('asc');
                var res = $(a).attr("status") > $(b).attr("status");
            }
            return res;

        });

        $('#container').html(statusList);
    });
  • 1

    The right thing would be to use css to mount the 'yes color and no color' scheme. Using nth-child(even) instead of style

1 answer

1


I suggest you do this with CSS and take the logic out of HTML colors:

#container div div:nth-child(2n){
    	background-color: #dcdcdc;
    }
    
    #container div div:nth-child(2n + 1){
    	background-color: #fff;
    }
<div>
    <div>id</div>
    <div><a id="orderStatus">status</a></div>
</div>
<div id="container">
    <div class="listStatus">
        <div>C</div>
        <div>1</div>
    </div>
    <div>
        <div class="listStatus">C</div>
        <div>2</div>
    </div>
    <div>
        <div class="listStatus">A</div>
        <div>3</div>
    </div>
    <input type="hidden" id="acao" value="asc" />
</div>

  • I ended up explaining myself badly and the understanding was another, the exit I want is the following id | status&#xA; c | 1&#xA; c | 2&#xA; a | 3&#Where id and status are one line, c and 1 are another line, c and 2 are another line, and finally a and 3 are another line. The above solution causes the columns to change color. But thanks for the tip, I didn’t know you could do this in CSS3

  • @Brunofolle ok, so you could do like this: https://jsfiddle.net/zw50xtx0/1/ also with CSS only...

  • 1

    Sergio, it worked!!! Thank you very much!

Browser other questions tagged

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