Search code examples
javascriptgoogle-apps-scriptgoogle-docsgoogle-docs-api

Creating a tooltip on word(s) in a text editor (Google Docs) using JavaScript/CSS


Intro: I'm working with Google Docs and have been trying (and struggling) to create a tooltip that pops up on selected (highlighted with cursor) words after the click of a button, for the purpose of creating notes for studying.

For example, if I have the words "Dynamic Programming" and I want to add the definition of it to the instances of "Dynamic Programming" so that when I hover/click on it, the definition will appear and I won't have to constantly scroll around or CTRL+F for it.

My question is if there is any advice on how to attach a tooltip to the selected text. I'm thinking of maybe creating a class="tooltip" and altering the inner HTML to include this class using xpath selection, but I'm struggling to put this idea into place. Are there any suggestions for how to approach this issue?

I've tried altering the selected text using the Document.ExecCommand(), like bolding it but there are no results. I see that this command is deprecated but I'm not sure what else I can use in its place. I wanted to use it's insertHTML().

My code so far:

I'm currently able to get the user's text selection (to attach the tooltip to), although it doesn't work entirely as planned. Even if you select only one word, it returns the entire line.

function createPopup(text) {

  var text = [];
  var selection = DocumentApp.getActiveDocument().getSelection().getSelectedElements(); 

  if (selection) {
    for (var i = 0; i < selection.length; i++) {
      text.push(selection[i].getElement().asText().getText());
    }

  DocumentApp.getUi().alert(text);

  }    
}

Solution

  • Answer:

    Unfortunately, this is not possible.

    More Information:

    enter image description here

    The tool-tip-like pop-ups that show for hyperlinks such as this one are not customisable and not a feature that is currently in Google Sheets.

    Workaround:

    You can use comments on cells which act similarly to these tooltips: hovering over the cell will reveal the comment like so:

    enter image description here

    Feature Request:

    Alternatively, if you would like something more customaible than cell comments, I would suggest filing a feature request to Google with the details.

    You can do this from the Google Sheets UI, by following the Help > Help Sheets improve menu item.

    There is also a feature request here which details being able to add and manipulate comments directly from Google Apps Script, so add a star to the issue to help its visibility.