Custom keyboard shortcuts for Google Docs (change color - background color)

Viewed 4309

I would like to change the ForegroundColor of a selected text in a Google Docs with a keyboard shortcut.

I could make the "change the ForegroundColor" part (with a menu item bound to the function setColor() ), but not the "keyboard shortcut part".

I found this code but I have trouble implementing it:

$(document).keydown(function(e){
  //CTRL + Q keydown combo
  if(e.ctrlKey && e.keyCode == 81){
    $( '#output' ).html("I've been pressed!");
  }
})

My difficulties :

1) I am not sure where to place this code in my script editor (I tried to place it in the onOpen() function as below, but also above it without success).

2) I am not sure what the $(document) should refer to.

3) I am not sure what they mean by "having to click on / activate the sidebar first for that to happen".

function onOpen() {
  var ui = DocumentApp.getUi();
  ui.createMenu('My Menu')
      .addItem('Color', 'setColor')
      .addToUi();

  var document = DocumentApp.getActiveDocument() // should it be here?
  $(document).keydown(function(e){
    //CTRL + Q keydown combo
    if(e.ctrlKey && e.keyCode == 81){
      SpreadsheetApp.getUi().alert('Hello, world!');
    }
  })
}

function setColor1() {
    var selection = DocumentApp.getActiveDocument().getSelection();
    if (selection) {
    var elements = selection.getRangeElements();
    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];

        // Only modify elements that can be edited as text; skip images and other non-text elements.
        if (element.getElement().editAsText) {
            var text = element.getElement().editAsText();

            // Edit the selected part of the element, or the full element if it's completely selected.
            if (element.isPartial()) {
                text.setForegroundColor(element.getStartOffset(), element.getEndOffsetInclusive(), "#00FFFF");
            } else {
                text.setForegroundColor("#00FFFF");
            }
        }
    }
    }
}
3 Answers
Related