Greasemonkey + Blogger HTML encode selection

Quick hit this week. Here is a Greasemonkey script I've been using for a few months. It adds a new button to your Blogger post editor which allows you to HTML encoded any selected text. This is useful if you include a lot of code examples in your blog. Download.

// ==UserScript==
// @name           Blogger - HTML encode on post edit
// @namespace      com.bitkickers
// @namespace
// @include        http*://*.g?*
// @require
// ==/UserScript==

function addButton() {

   $("#postButtons").append($("<div dir=\"ltr\" class=\"cssButtonSize-small cssButtonSide-left\"><div class=\"cssButtonColor-blue\"><a href=\"#\" class=\"cssButton\" id=\"encodeButton\"><div class=\"cssButtonOuter\"><div class=\"cssButtonMiddle\"><div class=\"cssButtonInner\">HTML Encode Selection</div></div></div></a></div></div>"));


function encode() {

   var editBox = $("#textarea")[0];
   if (typeof(editBox) != "undefined") {
      var originalScrollHeight = editBox.scrollTop;
      var selectedText = editBox.value.substring(editBox.selectionStart, editBox.selectionEnd);
      if (selectedText != "") {
         editBox.value = 
                  editBox.value.substring(0, editBox.selectionStart)
  + escapeHTML(selectedText)
                + editBox.value.substring(editBox.selectionEnd)
         editBox.scrollTop = originalScrollHeight;

function escapeHTML(str){
   var div = document.createElement('div');
   var text = document.createTextNode(str);
   return div.innerHTML;