Wednesday, June 26, 2013

contentEditable cross browser WYSIWYG

http://msdn.microsoft.com/en-us/library/ms533049(VS.85).aspx 

execCommand method
Syntax
object.execCommand(cmdID, showUI, value)

queryCommandEnabled method
Syntax
var flag = object.queryCommandEnabled(cmdID)


queryCommandIndeterm method
Syntax
object.queryCommandIndeterm(cmdID)

queryCommandState method
Syntax
object.queryCommandState(cmdID)

queryCommandSupported method
Syntax
var flag = object.queryCommandSupported(cmdID)

queryCommandValue method
Syntax
object.queryCommandValue(cmdID)


Command Return Description
AbsolutePosition false Required. Variant of type Boolean specifying whether the element is to be absolutely positioned.
BackColor false Required. Variant of type String that specifies a color name or a six-digit hexadecimal RGB value, with or without a leading hash mark.
BackgroundImageCache false Required. Variant of type Boolean specifying whether this feature is to be on or off.
Bold false Optional
Copy false Optional
CreateBookmark false Required. Variant of type String that specifies a valid anchor name. Providing an empty string will cause the command to fail.
CreateLink Optional. This command displays a dialogue box if the bUserInterface argument of execCommand is set to true or omitted. It does not display a dialogue box if the argument is set to false or null and the vValue parameter is present (even if it's null). Optional. Variant of type String that specifies a URL.
Cut false Optional
Delete false Optional
FontName false Required. Variant of type String that specifies a font name or font list, as described by the font attribute.
FontSize false Required. Variant of type Integer or String that specifies the font size. This must be a value between 1 and 7, inclusive.
ForeColor false Required. Variant of type String that specifies a color name or a six-digit hexadecimal RGB value, with or without a leading hash mark
FormatBlock false Required. Variant of type String that specifies a valid block format tag.
Indent false Optional
InsertButton false Optional. Variant of type String that specifies an id attribute for the button control.
InsertFieldset false Optional. Variant of type String that specifies an id attribute for the box. May be set to null or omitted.
InsertHorizontalRule false Optional. Variant of type String that specifies an id attribute for the horizontal line. May be set to null or omitted.
InsertIFrame false Optional. Variant of type String that specifies an id attribute for the inline frame. May be set to null or omitted.
InsertImage Optional. This command displays a dialogue box if the bUserInterface argument of execCommand is set to true or omitted. It does not display a dialogue box if the argument is set to false or null and the vValue parameter is present (even if it's null). Optional. Variant of type String that specifies the path and file name of the image to insert. If the command displays a dialogue box, this parameter is ignored.
InsertInputButton false Optional. Variant of type String that specifies an id attribute for the button control. May be set to null or omitted.
InsertInputCheckbox false Optional. Variant of type String that specifies an id attribute for the check box control. May be set to null or omitted.
InsertInputFileUpload false
InsertInputHidden false Optional. Variant of type String that specifies an id attribute for the check box control. May be set to null or omitted.
InsertInputImage false Optional. Variant of type String that specifies an id attribute for the check box control. May be set to null or omitted.
InsertInputPassword false Optional. Variant of type String that specifies an id attribute for the check box control. May be set to null or omitted.
InsertInputReset false Optional. Variant of type String that specifies an id attribute for the check box control. May be set to null or omitted.
InsertInputSubmit false Optional. Variant of type String that specifies an id attribute for the check box control. May be set to null or omitted.
InsertInputText false Optional. Variant of type String that specifies an id attribute for the check box control. May be set to null or omitted.
InsertMarquee false Optional. Variant of type String that specifies an id attribute for the marquee. May be set to null or omitted.
InsertOrderedList false Optional. Variant of type String that specifies an id attribute for the ordered list. May be set to null or omitted.
var tr = document.body.createTextRange();
tr.execCommand("InsertOrderedList", false, 'listId');
InsertParagraph false Optional. Variant of type String that specifies an id attribute for the paragraph. May be set to null or omitted.
InsertSelectDropdown false Optional. Variant of type String that specifies an id attribute for the drop-down selection control. May be set to null or omitted.
InsertSelectListbox false Optional. Variant of type String that specifies an id attribute for the list box selection control. May be set to null or omitted.
InsertTextArea false Optional. Variant of type String that specifies an id attribute for the text input control. May be set to null or omitted.
InsertUnorderedList false Optional. Variant of type String that specifies an id attribute for the unordered list. May be set to null or omitted.
var tr = document.body.createTextRange();
tr.execCommand("InsertUnorderedList", false, 'listId');
Italic false Optional
JustifyFull false Optional
JustifyLeft false Optional
JustifyNone false Optional
JustifyRight false Optional
LiveResize false Required. Variant of type Boolean specifying whether this feature is to be on or off.
MultipleSelection false Required. Variant of type Boolean specifying whether this feature is to be on or off. If multiple items are selected when the multiple selection feature is turned off, the items will remain selected.
Outdent false Optional
OverWrite false Optional. Variant of type Boolean that specifies the text-entry mode. If this value is set to true or null, the text-entry mode is overwrite. If this value is set to false (the default), the text-entry mode is insert.
Paste false Optional
Print false Optional
Refresh false Optional
RemoveFormat false Optional
SaveAs Optional. This command displays a dialogue box if nCmdExecOpt is set to MSOCMDEXECOPT_DODEFAULT, MSOCMDEXECOPT_PROMPTUSER, or null. It does not display a dialogue box if the argument is set to MSOCMDEXECOPT_DONTPROMPTUSER.This parameter is ignored. The Save HTML Document dialog box is always displayed. Optional. Variant of type String that specifies the path and file name of the file to which to save the Web page. When the path contains more than one folder name, separate the folder names with two backward slashes (\\).
SelectAll false Optional
SizeToControl false Optional
SizeToControlHeight false
StrikeThrough false
Subscript false
Superscript false
Underline false Optional
Undo false Optional,
Unlink false Optional
Unselect false Optional

Set caret position right after the inserted element in a contentEditable div


<input type="button" 
onclick="insertNodeAtCaret(document.createTextNode('[INSERTED]'));" 
value="Insert node" 
onfocus="document.getElementById('test').focus()">

<div contenteditable="true" id="test">Here is some editable text</div>
function insertNodeAtCaret(node) {
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0);
            range.collapse(false);
            range.insertNode(node);
            range = range.cloneRange();
            range.selectNodeContents(node);
            range.collapse(false);
            sel.removeAllRanges();
            sel.addRange(range);
        }
    } else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
        var html = (node.nodeType == 1) ? node.outerHTML : node.data;
        var id = "marker_" + ("" + Math.random()).slice(2);
        html += '<span id="' + id + '"></span>';
        var textRange = document.selection.createRange();
        textRange.collapse(false);
        textRange.pasteHTML(html);
        var markerSpan = document.getElementById(id);
        textRange.moveToElementText(markerSpan);
        textRange.select();
        markerSpan.parentNode.removeChild(markerSpan);
    }
}

Tuesday, June 25, 2013

Preserve text selection in contenteditable while interacting with jQuery

You could save and restore the selection using simple functions such as the following when the dialog is opened and closed. I am not familiar enough with jQuery dialogs to know the mechanism for hooking into the dialog opening and closing. The first, saveSelection, returns you a Range or TextRangeobject that you should store in a variable which you later pass to restoreSelection:
function saveSelection() {
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            return sel.getRangeAt(0);
        }
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange();
    }
    return null;
}

function restoreSelection(range) {
    if (range) {
        if (window.getSelection) {
            sel = window.getSelection();
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (document.selection && range.select) {
            range.select();
        }
    }
}

Monday, June 24, 2013

Calling a jQuery plugin's private function in setInterval()

(function($){
    $.fn.something = function(options)
    {
        var opts = $.extend({}, $.fn.something.defaults, options);
        return this.each(function()
        {
            var $this = $(this);
            $this.click(function(){
                startSomething($this);
            });
        });
        // Private function
        function startSomething($this)
        {
            // $this is defined
            setInterval(function(){
                doSomething($this);
            }, 1000);
        };
        // Another private function
        function doSomething($this)
        {
            // $this is undefined
            $this.toggle();
        };
    };
    $.fn.something.defaults = {
        my_option: 'value'
    };
})(jQuery);

$('#test').something();

jquery - Get file path of currently executing JavaScript code

scripts = document.getElementsByTagName("script");
$.each(scripts, function(i, v) {
    if (v.src.match("/sticky_note.js$")) {
        src = v.src.substring( 0, v.src.lastIndexOf( "/" ) ) + "/";
        console.log(src);
    }
});
scripts = document.getElementsByTagName("script");
$.each(scripts, function(i, v) {
    if (v.src.match("/sticky_note.js$")) { 
        src = v.src.substring( 0, v.src.lastIndexOf( "/" ) ) + "/";
        console.log(src);
    }
});

How to get selected(user-highlighted) text in contenteditable element and replace it?

<div class='a'>I am pritom</div>

var parent = $(".a");
parent.find("span.2406201317592000").remove();
var text = common__GetSelectionHtml();
if(parent.find("span.2406201317592000").length) { /* means text selected in this section */
    console.log(text);
}


function getSelectionHtml() {
    var html = "";
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var container = document.createElement("div");
            for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                container.appendChild(sel.getRangeAt(i).cloneContents());

                var newSpan = document.createElement("span");
                var range = sel.getRangeAt(i);
                newSpan.setAttribute('class','span_2406201317592000');
                $(newSpan).html("");
                //range.collapse(false);
                range.insertNode(newSpan);
            }
            html = container.innerHTML;
        }
    } else if (typeof document.selection != "undefined") {
        if (document.selection.type == "Text") {
            html = document.selection.createRange().htmlText;
        }
    }
    console.log(html);
}
 
 

function replaceSelectionWithHtml(html) {
    var range, html;
    if (window.getSelection && window.getSelection().getRangeAt) {
        range = window.getSelection().getRangeAt(0);
        range.deleteContents();
        var div = document.createElement("div");
        div.innerHTML = html;
        var frag = document.createDocumentFragment(), child;
        while ( (child = div.firstChild) ) {
            frag.appendChild(child);
        }
        range.insertNode(frag);
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        html = (node.nodeType == 3) ? node.data : node.outerHTML;
        range.pasteHTML(html);
    }
}

jQuery.fn.selectText = function(){
   var doc = document;
   var element = this[0];
   console.log(this, element);
   if (doc.body.createTextRange) {
       var range = document.body.createTextRange();
       range.moveToElementText(element);
       range.select();
   } else if (window.getSelection) {
       var selection = window.getSelection();        
       var range = document.createRange();
       range.selectNodeContents(element);
       selection.removeAllRanges();
       selection.addRange(range);
   }
};

$("button").click(function() {
    $("#editable").selectText();
});