Search code examples
javascripttriggerscopyslickgrid

Trigger cell copy (Ctrl+c) programatically with SlickGrid


I am using the copy/paste feature implemented in Slickgrid's slick.cellcopymanager.js which is working fine (i.e. if you select some cells and press Ctrl+c then the content of these cells will be copied into your clipboard).

I would like to trigger the Ctrl+c action programatically (for instance to allow doing copy/paste by clicking buttons instead of pressing keys). I know how to define the keydown event for Ctrl+c:

var e = jQuery.Event("keydown");        
e.which = 67;
e.ctrlKey = true;

however I just can't find out which object to trigger that event with and how so as to simulate the manual Ctrl+c. First I tried a simple trigger of the event which didn't work:

-div_dom_from_selected_cell.trigger(e); // nothing happens
-grid_dom_wrapper.trigger(e); // nothing happens
-$('body').trigger(e); // nothing happens
-my_grid.trigger(e); // trigger is not a function

Then I extended slick.cellcopymanager.js so as to make the handleKeyDown function available externally:

$.extend(this, {
  "init": init,
  "destroy": destroy,
  "clearCopySelection": clearCopySelection,
  "handleKeyDown": handleKeyDown,          // ADDED THIS LINE
  "onCopyCells": new Slick.Event(),
  "onCopyCancelled": new Slick.Event(),
  "onPasteCells": new Slick.Event()
});

And tried to use it:

var copyManager = new Slick.CellCopyManager();
copyManager.init(my_grid);
copyManager.handleKeyDown(e, { cell: cell, row: row, grid: my_grid } );

The copying of the cell still doesn't work despite:
-me having a cell properly selected (it has the selected class)
-handleKeyDown being fired properly
-e and args arguments inside handleKeyDown looking good (I'm tracing with console.log and can't see any difference between manual Ctrl+c and programatic attempt`

How can I trigger the Ctrl+c event so as to copy a cell programatically?


Solution

  • This worked for me running from the console on the example page.

    // Copy from row 2, column 5
    var row = 2, col = 5;
    grid.getSelectionModel().setSelectedRanges([new Slick.Range(row,col)]);
    var e = jQuery.Event("keydown");        
    e.which = 67;
    e.ctrlKey = true;
    grid.onKeyDown.notify(null, e);
    

    And then paste:

    // Past to row 3, column 4
    var row = 3, col = 4;
    grid.getSelectionModel().setSelectedRanges([new Slick.Range(row,col)]);
    var e = jQuery.Event("keydown");        
    e.which = 86;
    e.ctrlKey = true;
    grid.onKeyDown.notify(null, e);