1

I often email responses inline to questions. In order to differentiate my response, I like to give them a colour. This is quite onerous in Gmail, with about 3 clicks to get a colour applied. I would love a keyboard shortcut or browser bar on click Javascript hack to do this... so question is, how to figure this out.

1. Javascript edit the HTML by adding the tag around the selected words <font color="#ff9900">The words to be changed</font>

Maybe using the .wrap() function - but difficult to work out the selector for some selected text

2. Track the Gmail function that fires when the colour is selected in the Text Styling menu - who to track a function in Javascript? Hmmm stuck too. Then setting it off with a keyboard shortcut somehow?

  1. ??

Would love some help here. I am sure others would benefit from this hack too.

0

Inspired by https://stackoverflow.com/questions/5393922/javascript-replace-selection-all-browsers by @tim-down

Getting close, but needs a tweak if you see it, maybe edit my answer here:

<!-- language: lang-js -->

function wrapSelection(wrapSt, wrapEd, selectInserted) {
   var sel, range, fragment;

   if (typeof window.getSelection != "undefined") {
   // IE 9 and other non-IE browsers
   sel = window.getSelection();

   // Test that the Selection object contains at least one Range
   if (sel.getRangeAt && sel.rangeCount) {
     // Get the first Range (only Firefox supports more than one)
  range = window.getSelection().getRangeAt(0);
  range.deleteContents();

  // Create a DocumentFragment to wrap existing selection
  // Need to test for the existence of range.createContextualFragment
  // because it's non-standard and IE 9 does not support it
  if (range.createContextualFragment) {
    fragment = range.createContextualFragment(wrapSt + sel.anchorNode.textContent + wrapEd);
  } else {
    // In IE 9 we need to use innerHTML of a temporary element
    var div = document.createElement("div"),
      child;
    div.innerHTML = wrapSt + sel.anchorNode.textContent + wrapEd;
    fragment = document.createDocumentFragment();
    while ((child = div.firstChild)) {
      fragment.appendChild(child);
    }
  }
  var firstInsertedNode = fragment.firstChild;
  var lastInsertedNode = fragment.lastChild;
  range.insertNode(fragment);
  if (selectInserted) {
    if (firstInsertedNode) {
      range.setStartBefore(firstInsertedNode);
      range.setEndAfter(lastInsertedNode);
    }
    sel.removeAllRanges();
    sel.addRange(range);
  }
}
} else if (document.selection && document.selection.type != "Control") {
// IE 8 and below
range = document.selection.createRange();
range.pasteHTML(wrapSt + sel.anchorNode.textContent + wrapEd);
 }
}

https://jsfiddle.net/craiglambie/0em6wkz4/23/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.