Skip to main content Skip to footer

Change the Background Color of Cells after Edit in JavaScript

Background:

Users may want to keep track of cells that they have edited in the current session; one way this can be done is by changing the background color. This can be done by using things such as the itemFormatter method and the cellEditEnding event.

Steps to Complete:

1. Assign a function to the cellEditEnding event

2. In that function, push the row and column values onto a list of edited cells

3. Assign a function to the itemFormatter event

4. Check that we're in the cells panel, and if we are iterate through the list of cells and assign a background color to ones that have been added to the list of edited cells

Getting Started

Assign a function to the cellEditEnding event

Since we're going to be changing the background color of edited cells, we need to know when these cells actually get edited. This can be done by using the cellEditEnding event, which gets fired off when the cell has been edited but prior to the data being committed.

cellEditEnding: function(s, e) {}

In that function, push the row and column values onto a list of edited cells

We'll be using a list of objects to keep track of edited cells, and those objects will store the row and column value of the cells that have been edited. First, we'll need to check that the value in the cell has actually changed; if so, then we can push it onto the list.

if(s.getCellData(e.row, e.col) != s.activeEditor.value) {
    listOfEditedCells.push({ row: e.row, col: e.col });
}

Assign a function to the itemFormatter event

The itemFormatter event will get fired whenever a cell gets updated in the grid, because it needs to format the cells so that the content will correctly fit. We'll use this event to change the colors, but first we need to assign a function to the event.

itemFormatter: function(panel, r, c, cell) {}

Check that we're in the cells panel. If we are, iterate through the list of cells and assign a background color to ones that have been added to the list of edited cells

In the final step, we'll check that we're inside of the cells panel when we're inside of the itemFormatter. If we're inside the cells panel, we then check and see if the current cell matches the current index of our edited cell list. If they match, the background color style gets changed.

if(panel == grid.cells) {
    for(var i = 0; i < listOfEditedCells.length; i++) {
        if(listOfEditedCells[i].row == r && listOfEditedCells[i].column == c) {
            cell.style.backgroundColor = '#e0e0e0';
        }
    }
}

You can find a live sample of the project outlined in this article here: https://jsfiddle.net/JParksGC/pj51anv3/

Joel Parks