Context Menu

DataGridXL ships with a built-in context menu. You know, that menu that pops up when you right-click inside the component.

You can customize the items it holds. The contextMenuItems option takes an array of Context Menu Items:

Javascript
var grid = new DataGridXL("grid", {
  data: [ ... ],
  contextMenuItems: [
    "copy",
    "cut",
    "paste",
    "delete_rows",
    "insert_rows_before",
    "insert_rows_after",
    "delete_cols",
    "insert_cols_before",
    "insert_cols_after"
  ]
});

These string values like "copy" and "cut" are shortcuts to preset Context Menu Items.

The string "copy" refers to a Context Menu Item that actually looks like this:

Javascript
{
    "label": "Copy",
    "method": function(){
      this.copy();
    },
    "shortcutLabel": "Ctrl+C",
    "shortcutLabelMac": "⌘C"
}

Another example: "delete_rows" is a shortcut to this Context Menu Item:

Javascript
{
    "label": "Delete Rows",
    "method": function(){
      this.deleteRows(this.getRowSelection());
    },
    "disabled": function(){
      if(this.getRowSelection() == null){
        return true;
      } else {
        return false;
      }
    }
}

Notice that the predefined "Delete Rows" item has a disabled property; a function that must return either true or false.

The disabled function will run each time just before the context menu opens. This means that the "Delete Rows" menu item will be disabled (unselectable) when there is no row selection (at the time the context menu is opened).

We've created these predefined menu items to save you a bit of time & hassle in case you want to customize your context menu.

Custom Menu Items

These predefined items might not always be enough. As an example, we don't have a prefedined item for "Select All". In this case, you could supply this item yourself:

Javascript
{
    "label": "Select All",
    "method": function(){
      this.selectAll();
    },
    "shortcutLabel": "Ctrl+A",
    "shortcutLabelMac": "⌘A"
}

You can mix the predefined menu item shortcuts with your own menu items, like this:

Javascript
var grid = new DataGridXL("grid", {
  data: [ ... ],
  contextMenuItems: [
    "copy",
    "cut",
    {
      // my custom item
      "label": "Select All",
      "method": function(){
        this.selectAll();
      },
      "shortcutLabel": "Ctrl+A",
      "shortcutLabelMac": "⌘A"
    },
    "insert_rows"
  ]
});

Why haven't we included a predefined "Select All" item, you ask... Well, if we had we could not have written this tutorial. Clever!

Advanced

Should you console.log your DataGridXL instance, you'll see a private property named _presetContextMenuItems. As you might have guessed, these properties hold the predefined Context Menu items that you can include in your custom context menu.

Leave email to receive latest updates!