Search code examples
javascriptjqueryjquery-uirangeslider

How to change color in class nth-child() in jquery?


I want to make rating filter star using range slider jquery ui and set star color in class (.star-group) to red. for example, if value rating 1, I want to set color red in ( .star-group:nth-child(5) ) here the code:

$( "#slider-range" ).slider({
  orientation: "vertical",
  range: true,
  min: 1,
    max: 5,
    values: [2,4],
  slide: function( event, ui ) {
    $( "#amount" ).val( ui.values[ 0 ] + " - " + ui.values[ 1 ] );
    for(i=1; i<=ui.values[0];i++) {
        //$(".df:nth-child("+i+")").addClass('clgray');
      $(".star-group").addClass('red');
    }
  }
});
$( "#amount" ).val( $( "#slider-range" ).slider( "values", 0 ) + 
" - " + $( "#slider-range" ).slider( "values", 1 ) );

see more here: https://jsfiddle.net/equ92qn8/


Solution

  • Look here for the tested solution with comments added: https://jsfiddle.net/u3448okL/

    I added a few comments in the code, to see what I did. Please ask if anything is unclear.

    The correct code is:

    $( "#slider-range" ).slider({
      orientation: "vertical",
      range: true,
      min: 1,
        max: 5,
        values: [2,4],
      slide: function( event, ui ) {
        $( "#amount" ).val( ui.values[ 0 ] + " - " + ui.values[ 1 ] ); 
    
        // Reset to previous colors (by removing .red class)
        $(".star-group").removeClass('red');
    
        // For each group of stars ...
        $(".star-group").each(function(){
    
            // ... check if the number of stars in this object is in the VALUES INTERVAL, then add class RED        
            if ($(this).find('i').length >= ui.values[0] && $(this).find('i').length <= ui.values[1]){
                $(this).addClass('red');
             }
         })
      }
    });
    $( "#amount" ).val( $( "#slider-range" ).slider( "values", 0 ) + " - " + $( "#slider-range" ).slider( "values", 1 ) );  
    

    Please note that I avoided using nth-child() because of "safety". We could have done it with it, but in my opinion it was safer the way above.

    Please read here why nth-child can be tricky: JQuery nth-child not working properly