Forum Discussion

DanB's avatar
DanB
Data Storage
02-07-2022
Solved

Conditional Color Coding of Table Cells

Hello, fellow analytics enthusiasts.  I have a widget script that color codes table (not pivot) cells based on their values.  This code works, but only on the first page of table results.  If I switc...
  • harikm007's avatar
    02-07-2022

    DanB ,

    One method is to use 'MutationObserver'

    Please try this :

    widget.on('ready', function(se, ev) {
    	//Observer
    	const elementToObserve = $('.dataTables_scroll .dataTables_scrollBody table tbody', element)[0];
    	const observer = new MutationObserver(function(e) {
    		for(const m of e) {
    			if (m.type === 'childList') {
    				$("tr td:nth-child(4)").css('backgroundColor',''); // reset the color 
    				$("tr td:nth-child(4)").each(function() {
    
    				  if(parseInt($(this).html()) <= 14) {
    					$(this).css('backgroundColor','red');
    				   }
    				   if(parseInt($(this).html()) > 14 && parseInt($(this).html()) < 30) {
    					$(this).css('backgroundColor','yellow');
    				   }
    				   if(parseInt($(this).html()) > 30) {
    					$(this).css('backgroundColor','green');
    				   }
    				 });
    			}
    		}
    	});
    	observer.observe(elementToObserve, {subtree: true, childList: true});
    })

    -Hari