Customize Column Headers in Handsontable: A Quick Guide

Is there a way to customize the appearance of column headers in handsontable?

I have provided a jsfiddle example to showcase my current progress. While I am able to format the first row of data and change the column titles, I am facing difficulty in formatting the actual column headers.

var secondData = [
  ["2008", -0.5, 2, 2.2, -7],
  ["2009", -0.1, 3, 4.2, -2.6],
  ["2010", 3, 2, -1, 1]
];

var secondHeader = [
  {title: "Year", type: 'text'},
  {title: "Kia", type: 'numeric', format: '0.0%', renderer: percentRenderer},
  {title: "Nissan", type: 'numeric', format: '0.0%', renderer: percentRenderer},
  {title: "Toyota", type: 'numeric', format: '0.0%', renderer: percentRenderer},
  {title: "Honda", type: 'numeric', format: '0.0%', renderer: percentRenderer}
];

$("#headerGrid").handsontable({
  data: secondData,
  columns: secondHeader,
  minSpareCols: 0,
  minSpareRows: 0,
  rowHeaders: false,
  colHeaders: true,
  contextMenu: true,
  cells: function (row, col, prop) {
    var cellProperties = {};
    if (row === 0) {
      cellProperties.renderer = firstRowRenderer; 
    }
    return cellProperties;
  }
});

function percentRenderer (instance, td, row, col, prop, value, cellProperties) {
  Handsontable.renderers.NumericRenderer.apply(this, arguments);
  td.style.color = (value < 0) ? 'red' : 'green';
};

function firstRowRenderer(instance, td, row, col, prop, value, cellProperties) {
  Handsontable.renderers.TextRenderer.apply(this, arguments);
  td.style.fontWeight = 'bold';
  td.style.color = 'green';
  td.style.background = '#CEC';
}

Answer №1

One way to customize Handsontable is by tweaking its CSS for th styling in order to format the cells. To change the appearance of a single header, you can adjust the CSS code as shown below:

.handsontable th:nth-child(1){
    background-color:aquamarine;
    font-weight:bold;
}

You can also utilize HTML within the columns property titles using elements like span to style the text while keeping the cell unaffected by CSS formatting.

var secondHeader = [
  {title: "Year", type: 'text'},
  {title: "Kia", type: 'numeric', format: '0.0%', renderer: percentRenderer},
  {title: "<span class='headerBold'>Nissan</span>", type: 'numeric', format: '0.0%', renderer: percentRenderer},
  {title: "Toyota", type: 'numeric', format: '0.0%', renderer: percentRenderer},
  {title: "Honda", type: 'numeric', format: '0.0%', renderer: percentRenderer}

];

span.headerBold{
    font-weight:bold;
}

For the updated version of the script, visit this link on jsfiddle.

Answer №2

Currently, the custom renderers do not affect headers. However, there are two options available to work around this limitation. The first option is demonstrated in the documentation with an example of rendering HTML in the headers:

colHeaders: function(col) {
    var txt;

    switch (col) {
        case 0:
            return '<b>Bold</b> and <em>Beautiful</em>';

        case 1:
            txt = "Some <input type='checkbox' class='checker' ";
            txt += isChecked ? 'checked="checked"' : '';
            txt += "> checkbox";

            return txt;
    }
}

This approach allows for dynamic changes to the header content by including HTML elements. If dynamic changes are not necessary, headers can simply be defined with HTML content.

The second option, for dynamically changing headers, involves defining headers statically as mentioned earlier and updating them through events. For instance, if you want a column header to reflect a cell's validation status, you can create an event within the afterChange Handsontable event. This event can trigger a function like the following:

var headers = ['First col', 'Second col', 'Third col'];

/**
 * A custom function that dynamically updates the content in the header.
 * @param  {Array} cellsNotValidated    Array of column indices not validated.
 */
function updateHeader(cellsNotValidated) {
    for (var i = 0; i <= headers.length - 1; i++) {
        var cellHeaderSelector = $(headers[i]);
        var cellNotValidated = cellsNotValidated.indexOf(i) >= 0;

        if (cellNotValidated) {
            headers[i] = cellHeaderSelector.addClass('notValidated');
        } else {
            headers[i] = cellHeaderSelector.removeClass('notValidated');
        }
    };

    hotInstance.updateSettings({
        colHeaders: headers
    });
}

By applying classes to the headers, you can dynamically adjust their styling based on specific conditions. This method allows for a flexible and dynamic header definition. Hopefully, this explanation clarifies the process!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Decoding a changeable JSON structure

As I am working on parsing a JSON and looking for a specific key within the JSON object, I am facing an issue due to the changing structure of the JSON. It is not feasible to hard code the path for searching. Are there any alternative methods to parse this ...

Executing JavaScript POST Requests Based on User Input Changes

Hey there! I'm working on a feature where the input value is populated based on the selection in a dropdown menu. The idea is that when the user picks a code, the corresponding amount will be displayed. However, I want the select box to retain its or ...

Disappearing Data in Chart.js When Window is Resized

I am utilizing the Chart.js library to present a line chart in a div that is enclosed within a <tr>. <tr class="item">...</tr> <tr class="item-details"> ... <div class="col-sm-6 col-xs-12 chart-pane"> <div clas ...

The class functions perfectly under regular circumstances but ceases to operate once it is initialized

I'm currently developing a bluetooth remote in React Native. The issue I am facing is that my BLE class works perfectly on its own, but certain sections of code seem to malfunction when implemented within another class. import BLE from './Core/BL ...

Setting the borderRadius for a web view on Android Maps V3: A complete guide

In my application, I am using Android Map V3 and have encountered a bug specific to the Kit-Kat version. The chromium kit throws up an error message - nativeOnDraw failed; clearing to background color, which prevents the map from being displayed. Despite ...

The Google Maps application is experiencing an issue with rendering maps

Here is my code without the google map key. I am not receiving any errors, but the map is not showing up. What could I be missing? To test it out yourself, you will need to add your own map key which you can obtain from here. <!DOCTYPE html> <h ...

JavaScript toggle display function not functioning properly when clicked

I've been attempting to create a drop-down list using HTML and JavaScript, but for some inexplicable reason, it's just not functioning as expected despite scouring through countless tutorials on YouTube. Below is the snippet of code that I'm ...

User input determines the path of Iron Route in Meteor

A requirement is to execute a function that prompts the user for input and then navigates to that specified value. For instance, if the inserted value is: https://www.youtube.com/watch?v=_ZiN_NqT-Us The intended destination URL should be: download?u ...

Slider for jQuery or Ajax framework

Currently, I am in search of a gauge that contains multiple concentric circles, with each circle displaying values of different entities, similar to the image provided. Each individual needle indicates the value of its corresponding entity. I have come a ...

What triggers the invocation of the onerror handler in XMLHttpRequest?

I am facing a bit of confusion when trying to understand the functionality of XMLHttpRequest's handlers. After reading the specification regarding the onerror handler, it mentions: error [Dispatched ... ] When the request has failed. load [Dispa ...

Issue with highlighting when one string overlaps with another

I am facing a challenge with handling a string that contains Lorem Ipsum text. I have JSON data that specifies the start and end offsets of certain sections within the text that I need to highlight. The approach I am currently using involves sorting the JS ...

Animating CSS using JavaScript

Recently diving into the world of JavaScript, I've taken on the challenge of creating an analog clock. I began by crafting the second hand using CSS but now I'm eager to transition it to Javascript without relying on jQuery or any other JS framew ...

Firefox 3 fails to utilize cache when an ajax request is made while the page is loading

Upon loading the page DOM, I utilize jQuery to fetch JSON data via ajax like so: $(document).ready(function(){ getData(); }); ...where the function getData() executes a basic jQuery ajax call similar to this: function getData(){ $.ajax({cache: t ...

Struggling to construct a project using parcel, continually encountering issues with unsupported file types

My attempt at creating a project using parcel has hit a snag. Despite diligently following the guidelines provided in my assignment, an error message consistently appears in my terminal each time I initiate the command: parcel src/index.html The error mes ...

Is relying on getState in Redux considered clunky or ineffective?

Imagine a scenario where the global store contains numerous entities. Oranges Markets Sodas If you want to create a function called getOrangeSodaPrice, there are multiple ways to achieve this: Using parameters function getOrangeSodaPrice(oranges, s ...

Guide on sending data to MongoDB using Postman

I am currently facing an issue while trying to send data to the MongoDB database using Postman. Despite everything seeming fine, I keep encountering errors. https://i.stack.imgur.com/Gcf5Q.jpg https://i.stack.imgur.com/ntjwu.jpg https://i.stack.imgur.co ...

implement a dropdown feature for a vertical menu with the help of Jquery

Struggling to implement a dropdown feature on a vertical navigation using Jquery. The HTML includes a nav section with 1st level list items and nested li's for second level menu items. On clicking the 1st level li, the intention is to toggle SHOW/HID ...

The alignment of the first and second steps in Intro.js and Intro.js-react is off

There seems to be an issue here. Upon reloading, the initial step and pop-up appear in the upper left corner instead of the center, which is not what I anticipated based on the Intro.js official documentation. https://i.stack.imgur.com/ICiGt.png Further ...

AngularJS is throwing an error because the current.$$route object is not defined

Having worked with AngularJS, I encountered an error when trying to set a title. Here is my App.js 'use strict'; var serviceBase = 'http://www.yiiangular.dev/' var spaApp = angular.module('spaApp', [ 'ngRoute' ...

The modal template in Angular UI is not displaying properly with Bootstrap styling

I've been working on displaying a modal template when a row is selected on a table. The issue I'm facing is that upon clicking a row, a 2px thick black shadowed line appears, which seems to represent the modal but doesn't display its conten ...