When a cell is selected in SlickGrid, how can I apply a class to it's column header?
If you look at Excel or Google docs, both apply an effect to the header cell to give a visual indication of which cell is selected. I want to add this effect to SlickGrid, but I am not sure how.
The headerCssClass
column option will apply styling to the cells but that would require the headers to be rendered again to apply the changes.
So the primary events of concern are onActiveCellChanged
and if applicable onColumnsReordered
. I've chosen instead to subscribe to onHeaderRowCellRendered
as that will also be called after a column reorder.
<html>
<link rel="stylesheet" type="text/css" href="http://mleibman.github.io/SlickGrid/slick.grid.css">
<link rel="stylesheet" href="http://mleibman.github.io/SlickGrid/examples/examples.css" type="text/css"/>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.min.js"></script>
<script src="http://mleibman.github.io/SlickGrid/lib/jquery.event.drag-2.2.js"></script>
<script src="http://mleibman.github.io/SlickGrid/slick.core.js"></script>
<script src="http://mleibman.github.io/SlickGrid/slick.grid.js"></script>
<style>
.selected_header {
background: #b8f8A8;
}
</style>
<div id="myGrid" style="width:500px;height:100px;"></div>
<script>
var grid;
var data = [];
var columns = [
{id: "server", name: "Server", field: "server", width: 180}
];
for (var i = 0; i < 4; i++) {
columns.push({
id: "id" + i,
name: "Id" + i,
field: i
});
}
var options = {
editable: false,
showHeaderRow: true,
headerRowHeight: 30,
enableCellNavigation: true
};
$(function () {
for (var i = 0; i < 5; i++) {
var d = (data[i] = {});
d.server = "Server " + i;
for (var j = 0; j < columns.length; j++) {
d[j] = Math.round(Math.random() * 100);
}
}
grid = new Slick.Grid("#myGrid", data, columns, options);
grid.onActiveCellChanged.subscribe(function(e, args){
var headerColumns = $('.slick-header-columns').children();
for(i = 0; i< headerColumns.length; ++i){
$(headerColumns[i])[i == args.cell ? "addClass" : "removeClass" ]('selected_header')
}
})
grid.onHeaderRowCellRendered.subscribe(function(e, args){
if(grid.getActiveCell() ){
var columnIndex = grid.getActiveCell().cell
var headers = $('.slick-header-columns').children()
if(headers.length < columnIndex){return;}
$(headers[columnIndex]).addClass('selected_header')
}
})
});
</script>
</html>