In the above snippet, a handsontable is created with a hook that adds a column automatically (using this.alter('insert_col')
) once a user presses "right" in the rightmost column (and also removes an empty rightmost column if a user presses "left" from there). The issue with it, as you may see, is that once a column added in this manner, colHeaders shift to the right instead of staying with their columns. Is this a bug or I am doing something wrong? How do I fix this or is there a workaround?
document.addEventListener("DOMContentLoaded", function() {
var example = document.getElementById('example1'),
hot = new Handsontable(example,{
data: Handsontable.helper.createSpreadsheetData(2, 3),
colHeaders: ["one","two","three"],
contextMenu: true
});
Handsontable.hooks.add('beforeKeyDown',function(event)
{
var $right = 39, $left = 37,
selected = this.getSelected(),
isEditMode = this.getActiveEditor().isOpened();
if(isEditMode) return;
// calc dimensions
var startColNum = selected ? (selected[1]+1) : null,
endColNum = selected ? (selected[3]+1) : null,
// endColNum is not necessarily >= startColNum, it is where selection /has ended/
rowsNum = this.countRows(),
colsNum = this.countCols(),
isFirstCol = endColNum == 0,
isLastCol = endColNum == colsNum,
i, noData, data = this.getData();
// handle arrow keys
if(isLastCol) {
if(event.which == $right)
this.alter('insert_col');
if(event.which == $left && !isFirstCol) {
noData = true;
for(i = 0; i < rowsNum; i++)
if(data[i][endColNum-1])
noData = false;
if(noData) {
this.alter('remove_col');
Handsontable.Dom.stopImmediatePropagation(event);
// don't scroll the page
if(event.preventDefault)
event.preventDefault();
}
}
}
});
});
<script src="https://docs.handsontable.com/pro/1.10.2/bower_components/handsontable-pro/dist/handsontable.full.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://docs.handsontable.com/pro/1.10.2/bower_components/handsontable-pro/dist/handsontable.full.min.css">
<div id="example1" class="hot handsontable"></div>
As IronGeek suggest in the comment, adding the index as the second parameter to the function alter fix your issue :
this.alter('insert_col', endColNum);
However, I do believe that you are still right saying that it is a bug since the documentation specify that if the paramater index is null or undefined :
[...] the new column will be added after the last column.
Find this JSFiddle for quickly testing the fix.