top of page

Colored labels in Table widget

If there are more rows in table widget its bit difficult to find a particular item from a column. But it will be easy if we applied different colors to different items in the column. Here is a script to apply styles to each items in table widget.



Steps:

  1. Create a table widget

  2. Add below widget script.

  3. Update the variable columnIndex with index of column to which color should be applied. (index is a number assigned to columns starting with 1. In above screenshot, State column has index 1, Country has index 2 and Region has index 3)

  4. Update the variable itemStyleMapping with mapping of item to style. Style can be background color, font color, padding etc.

  5. Save the script and refresh widget


widget.on('domready', function(se, ev){
	
	let columnsIndex = 3
	
	let itemStyleMapping = {
		'West':'background-color:#e64c72; color:white; padding: 2px 8px; border-radius:15px',
		'South': 'background-color:#e69545; color:white; padding: 2px 8px; border-radius:15px',
		'Northeast': 'background-color:#5f5da8; color:white; padding: 2px 8px; border-radius:15px',
		'Midwest': 'background-color:#4a9455; color:white; padding: 2px 8px; border-radius:15px',
		'Unknown': 'background-color:#8c8b8c; color:white; padding: 2px 8px; border-radius:15px'
	}
	const elementToObserve = $('table tbody', element)[0];
	
	$(elementToObserve).find(`tr td:nth-child(${columnsIndex})`).each(function(index, value){
		var label = $(this).text()
		
		if(label in itemStyleMapping)
		{
			$(this).text('')
			$(this).prepend(`<mark style="${itemStyleMapping[label]}">${label}</mark>`)
		}
						
	})
	
	const observer = new MutationObserver(function(e) {
		for(const m of e) {
			if (m.type === 'childList') {
				$.each(m.addedNodes, function(index, value){

					elementObj = $(value).find('td:nth-child(3)')
					var label = elementObj.text()

					if(label in itemStyleMapping)
					{
						elementObj.text('')
						elementObj.prepend(`<mark style="${itemStyleMapping[label]}">${label}</mark>`)
					}
				})
			}
		}
	})
										  
	observer.observe(elementToObserve, {subtree: true, childList: true});

})

351 views1 comment

Recent Posts

See All

1 commentaire


Ross Vickers
Ross Vickers
04 janv.

Is there a version of this for multiple coloumns?

J'aime
bottom of page