Denis Bobrovnikov
Denis Bobrovnikov

Reputation: 63

JavaScript WYSIWYG Rich Text Editor

What is the basic method of styling text inside input boxes? Can you show me the most simple example of how to change text color separately?

Upvotes: 3

Views: 1175

Answers (2)

shakthydoss
shakthydoss

Reputation: 2631

Very simply:

window.document.designMode = “On”;

document.execCommand(‘ForeColor’, false, ‘red’);

For more detail:

http://shakthydoss.com/javascript/html-rich-text-editor/

and then

http://shakthydoss.com/javascript/stxe-html-rich-text-editor/

Upvotes: 3

Amit Kumar Gupta
Amit Kumar Gupta

Reputation: 7413

There are 4 approaches you can adopt

  1. Create a textarea. Let user modify the content. On key press or button click insertHtml to preview div. Trix uses the same approach but programmatically.
  2. Add some textarea. Use some markdown processor which can render the the content of textarea.
  3. Handle every movement of blinking cursor and implement something like Google docs which doesn't use execCommands. I believe quilljs also doesn't use execCommands.
  4. You can use execCommands which are supported by almost all modern browsers. Here is the simplest example. Or check this example which uses this small code to run set of execCommands to make a rich text editor. You can simplify it more.

Example

angular.module("myApp", [])
    .directive("click", function () {
        return {
            restrict: "A",
            link: function (scope, element, attrs) {
                element.bind("click", function () {
                    scope.$evalAsync(attrs.click);
                });
            }
        };
    })
    .controller("Example", function ($scope) {
        $scope.supported = function (cmd) {
            var css = !!document.queryCommandSupported(cmd.cmd) ? "btn-succes" : "btn-error"
            return css
        };
        $scope.icon = function (cmd) {
            return (typeof cmd.icon !== "undefined") ? "fa fa-" + cmd.icon : "";
        };
        $scope.doCommand = function (cmd) {
            if ($scope.supported(cmd) === "btn-error") {
                alert("execCommand(“" + cmd.cmd + "”)\nis not supported in your browser");
                return;
            }
            val = (typeof cmd.val !== "undefined") ? prompt("Value for " + cmd.cmd + "?", cmd.val) : "";
            document.execCommand(cmd.cmd, false, (cmd.val || ""));
        }
        $scope.commands = commands;
        $scope.tags = [
    'Bootstrap', 'AngularJS', 'execCommand'
  ]
    })

Upvotes: 0

Related Questions