How to get even array index and change it background color

Right now i want to write a function to get the even array index and dynamically change it background color

enter image description here

Just like the image show above i want select the list item and change it background image.

2 answers

  • answered 2019-05-15 03:12 Vishrut Mavani

    You can achieve this using odd-even index of an array.

    In JavaScript you can achieve using below code.

    $('.js-toprow').each(function(index) {
        if (index % 2 === 0) { // Even
          $(this).css('background', '#ddd');
        } else { // Odd
          $(this).css('background', '#ff0000');
        }        
    });
    

    In Android, you can achieve using below code.

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {  
        View view = super.getView(position, convertView, parent);  
        if (position % 2 == 1) {
            view.setBackgroundColor(Color.BLUE);  
        } else {
            view.setBackgroundColor(Color.CYAN);  
        }
        return view;  
    }
    

    In React-Native you can achieve using below code.

    renderRow(rowData, sectionID, rowID) {
    
       let style = [
             styles.row, 
             {'backgroundColor': colors[rowID % colors.length]}
           ];
    
       return (<View style={style}/>);
     }
    
     let colors = ['#123456', '#654321', '#fdecba', '#abcdef'];
    
     let styles = StyleSheet.create({
           row: {
                // .. rows style
           }
     });
    

    OR

    (Provided Array).map((array, index) => {
            return (
                <View style={{ backgroundColor: (index % 2 == 0) ? '#ecf0f1' : '#fff' }}>
                    <Text>{array.key}</Text>
                </View>
            )
        })
    

  • answered 2019-05-15 03:25 Ikhide Eboreime

    If you're using jQuery,

    $('.items').filter(function(index){ return index % 2 === 0; }).css({ background: 'black', });