Make a custom text editor (styler) with JS - javascript

I have been asked to create a text editor with the following features:
Import text from another source
Apply styles to the text
Styles are predefined (for example style "Level 1" may make the text bold, green and italic.
One styling effect is to add characters before and after the selection so for example, text has two stars before and after
Styles are applied to full words, no partials
The text cannot be edited/changed, only styles should be added
The article text must be saved in a version-ed manor, for example Editor A added these changes ____ on date / timestamp.
What is the best way to do this?
I have been playing with execCommand and this does most of what I want, except I cant seem to make the text non-editable, I'm not able to add chars before and after the selection like this, and I cant track individual changes.
I'm almost thinking I should make each word a label and treat them like objects but I'm having a hard time making them select-able (highlight the text with the mouse like you do in an editor).
Does anyone know of any libraries for this sort of thing?

I can give you a part of the solution: how to select full words. My script is for textarea but you can make a few changes if you want to use div contenteditable instead.
JSFIDDLE DEMO
var lastSelectStart = 0;
var lastSelectEnd = 0;
saveSelection = function(){
lastSelectStart = document.getElementById("text").selectionStart;
lastSelectEnd = document.getElementById("text").selectionEnd;
}
selectWords = function(){
var divEditable = document.getElementById("text");
html = divEditable.innerHTML;
var start = lastSelectStart;
var end = lastSelectEnd;
var before = html.substring(0,start);
var after = html.substring(end);
var split = before.match(/[ .,;]/gi);
var startIndex = before.lastIndexOf(split[split.length-1]) + 1;
split = after.match(/[ .,;]/gi);
var endIndex = after.indexOf(split[0]);
endIndex = end + endIndex;
divEditable.selectionStart = startIndex;
divEditable.selectionEnd = endIndex;
// startIndex is where you insert your stars and
// (endIndex + number of stars added) is where you insert your stars again
}

Related

Any way to prevent losing focus when clicking an input text out of tinymce container?

I've made this tinymce fiddle to show what I say.
Highlight text in the editor, then click on the input text, highlight in tinyMCE is lost (obviously).
Now, I know it's not easy since both, the inline editor and the input text are in the same document, thus, the focus is only one. But is there any tinymce way to get like an "unfocused" highlight (gray color) whenever I click in an input text?
I'm saying this because I have a customized color picker, this color picker has an input where you can type in the HEX value, when clicking OK it would execCommand a color change on the selected text, but it looks ugly because the highlight is lost.
I don't want to use an iframe, I know that by using the non-inline editor (iframe) is one of the solutions, but for a few reasons, i can't use an iframe text editor.
Any suggestion here? Thanks.
P.S: Out of topic, does any of you guys know why I can't access to tinymce object in the tinyMCE Fiddle ? looks like the tinyMCE global var was overwritten by the tinymce select dom element of the page itself. I can't execute a tinyMCE command lol.
Another solution:
http://fiddle.tinymce.com/sBeaab/5
P.S: Out of topic, does any of you guys know why I can't access to
tinymce object in the tinyMCE Fiddle ? looks like the tinyMCE global
var was overwritten by the tinymce select dom element of the page
itself. I can't execute a tinyMCE command lol.
Well, you can access the tinyMCE variable and even execute commands.
this line is wrong
var colorHex = document.getElementById("colorHex")
colorHex contains input element, not value.
var colorHex = document.getElementById("colorHex").value
now it works ( neolist couldn't load, so I removed it )
http://fiddle.tinymce.com/DBeaab/1
I had to do something similar recently.
First off, you can't really have two different elements "selected" simultaneously. So in order to accomplish this you're going to need to mimic the browser's built-in 'selected text highlight'. To do this, you're going to have to insert spans into the text to simulate highlighting, and then capture the mousedown and mouseup events.
Here's a fiddle from StackOverflow user "fullpipe" which illustrates the technique I used.
http://jsfiddle.net/fullpipe/DpP7w/light/
$(document).ready(function() {
var keylist = "abcdefghijklmnopqrstuvwxyz123456789";
function randWord(length) {
var temp = '';
for (var i=0; i < length; i++)
temp += keylist.charAt(Math.floor(Math.random()*keylist.length));
return temp;
}
for(var i = 0; i < 500; i++) {
var len = Math.round(Math.random() * 5 + 3);
document.body.innerHTML += '<span id="'+ i +'">' + randWord(len) + '</span> ';
}
var start = null;
var end = null;
$('body').on('mousedown', function(event) {
start = null;
end = null;
$('span.s').removeClass('s');
start = $(event.target);
start.addClass('s');
});
$('body').on('mouseup', function(event) {
end = $(event.target);
end.addClass('s');
if(start && end) {
var between = getAllBetween(start,end);
for(var i=0, len=between.length; i<len;i++)
between[i].addClass('s');
alert('You select ' + (len) + ' words');
}
});
});
function getAllBetween(firstEl,lastEl) {
var firstIdx = $('span').index($(firstEl));
var lastIdx = $('span').index($(lastEl));
if(lastIdx == firstIdx)
return [$(firstEl)];
if(lastIdx > firstIdx) {
var firstElement = $(firstEl);
var lastElement = $(lastEl);
} else {
var lastElement = $(firstEl);
var firstElement = $(lastEl);
}
var collection = new Array();
collection.push(firstElement);
firstElement.nextAll().each(function(){
var siblingID = $(this).attr("id");
if (siblingID != $(lastElement).attr("id")) {
collection.push($(this));
} else {
return false;
}
});
collection.push(lastElement);
return collection;
}
As you can see in the fiddle, the gibberish text in the right pane stays highlighted regardless of focus elsewhere on the page.
At that point, you're going to have to apply your color changes to all matching spans.

Highlight all comma's in page with jquery

I have a very very simple question and i didn't find my answer.
I have a page that is using ajax and it gets update again and again in one div of it.
Now, i want to Highlight ALL the commas , of that div.
For example, they get red color.
How can i do it with this ajax page ?
I also wanted to try with this code, but i coudn't
$(document":contains(',')").css("color","red");
I just need to find all the commas in that div every second and give a style to them .
How to do it with jquery?
Don't know about jQuery, but it can be done with pure javascript. But it's not so easy actually.
tl;dr jsFiddle
This answer does not cause DOM revalidation and does not mess-up with javascript events!
First you need to loop through page content and replace every comma (or every character) with a <span> or other node so that you can give it individual CSS style. Let's start with getting textNodes:
HTMLElement.prototype.getTextNodes = function(recursive, uselist) {
var list = this.childNodes;
var nodes = uselist!=null?uselist:[];
for(var i=0,l=list.length; i<l;i++) {
if(list[i].nodeType==Node.TEXT_NODE) {
nodes.push(list[i]);
}
else if(recursive==true&&list[i].nodeType==1&&list[i].tagName.toLowerCase()!="script"&&list[i].tagName.toLowerCase()!="style") {
list[i].getTextNodes(true, nodes);
}
}
//console.log(nodes);
return nodes;
}
You'll now need to split the spans wherever the commas are:
/*Turn single text node into many spans containing single letters */
/* #param
textNode - HTMLTextNode element
highlight - the character to highlight
#return
null
*/
function replaceLetters(textNode, highlight) {
//Get the string contained in the text node
var text = textNode.data;
//Generate a container to contain text-node data
var container = document.createElement("span");
//Create another span for every single letter
var tinyNodes = [];
//Split the letters in spans
for(var i=0,l=text.length;i<l; i++) {
//skip whitespace
if(text[i].match(/^\s*$/)) {
container.appendChild(document.createTextNode(text[i]));
}
//Create a span with the letter
else {
//Create a span
var tiny = document.createElement("span");
//If the letter is our character
if(text[i]==highlight)
tiny.className = "highlighted";
tiny.innerHTML = text[i];
container.appendChild(tiny);
}
}
//replace text node with a span
textNode.parentNode.insertBefore(container, textNode);
textNode.parentNode.removeChild(textNode);
}
The function above was originaly used for animating all letters on a page (even when it was already loaded). You only need to change color of some of these.
If the functions above are defined, call this:
var nodes = document.getElementById("myDiv").getTextNodes(true);
for(var i=0, l=nodes.length; i<l; i++) {
replaceLetters(nodes[i], ",");
}
You need to wrap the commas with an HTML tag (such as <span>).
$(window).load(function() {
$('.target').each(function() {
var string = $(this).html();
$(this).html(string.replace(/,/g , '<span class="comma">,</span>'));
});
});
Here is an example:
http://jsfiddle.net/5mh6ja1L/
I don't know how to do it in jQuery but in pure JavaScript it would be something like this:
var el = document.getElementById("content");
el.innerHTML = el.innerHTML.replace(/,/g, "<b class='highlight'>,</b>");
demo: http://jsfiddle.net/f9xs0c79/
No need to do loop. You can just select the container where you want to replace and replace.
$("p").html(
$("p").html().replace(/,/g,"<span class='comma'>,</span>")
);
http://jsfiddle.net/1570ya75/2/

How to highlight an editable word in dynamically generated text?

Intro
I am creating a content editor in which I want to add the functionality to choose a word which you would like to be highlighted while typing your content.
At this moment I achieved to search any word chosen in the #dynamicWord and then typed in #contentAreaContainer and give it a red border by adding em around the keyword and style the em trough CSS:
Part of the Code:
<div class="word">
Dynamic word to highlight: <input name="dynamic_word" id="dynamicWord" value="Enter word..">
</div>
<div id="contentAreaContainer" oninput="highlighter()">
<textarea id="contentArea"></textarea>
</div>
function highlighter()
{
var contentAreaContainer = document.getElementById('contentAreaContainer');
var dynamicWord = document.getElementById('dynamicWord').value;
wrapWord(contentAreaContainer, dynamicWord);
};
wrapWord() does:
function wrapWord(el, word)
{
var expr = new RegExp(word, "i");
var nodes = [].slice.call(el.childNodes, 0);
for (var i = 0; i < nodes.length; i++)
{
var node = nodes[i];
if (node.nodeType == 3) // textNode
{
var matches = node.nodeValue.match(expr);
if (matches)
{
var parts = node.nodeValue.split(expr);
for (var n = 0; n < parts.length; n++)
{
if (n)
{
var em = el.insertBefore(document.createElement("em"), node);
em.appendChild(document.createTextNode(matches[n - 1]));
}
if (parts[n])
{
el.insertBefore(document.createTextNode(parts[n]), node);
}
}
el.removeChild(node);
}
}
else
{
wrapWord(node, word);
}
}
}
em{border: 1px solid red;}
The problem:
Now at this moment every time on input in #contentAreaContainer the keyword chosen is highlighted a short period in the #contentAreaContainer, because highlighter() is triggered on input. But it should stay highlighted after finding it instead of only oninput.
I need oninput to search for the #dynamicWord value with wrapWord() while some one is typing;
Any time the #dynamicWord value was found it should permanently get an em
So how can I sort of 'save' the found keywords and permanently give them the element until the dynamic keyword gets edited?
Check the DEMO version
Solved:
Using setTimeout() instead of oninput I managed to make the highlight look constant. The change:
function highlighter()
{
var contentAreaContainer = document.getElementById('contentAreaContainer');
var mainKeyword = document.getElementById('main_keyword').value;
wrapWord(contentAreaContainer, mainKeyword);
repeater = setTimeout(highlighter, 0.1);
}
highlighter();
I removed oninput="highlighter()" from #contentAreaContainer.
You are trying to highlight words in a textarea. As far as I know a textarea does not support html elements inside. If you do it would simply display them as text.
Therefore you need to use an editable div. This is a normal div but if you add the attribute:
contentEditable="true"
the div acts like a textarea with the only difference it now process html elements. I also needed to change the onchange event into the onkeyup event. The editable div does not support onchange events so the highlight would not be triggered. The HTML for this div looks like:
<div contentEditable="true" id="contentArea">Test text with a word in it</div>
Here is the working code in a fiddle: http://jsfiddle.net/Q6bGJ/ When you enter a new character in the textarea your keyword gets highlighted.
However there is still a problem left. You surround the keyword with an em element. This results in surrounding it on every keystroke. Now you end up width many em's around the keyword. How to solve this, I leave up to you as a challenge.

Javascript Gets the contents of the textarea of the distance from the border pixels

How can I be sure the text in the input box, the number of pixels from the left box? It may have utf8, Chinese
This might not be the best way, but i guess this can be a start. This will return the number of pixels remaining in the input element:
function getRemainingWidth(element){
var span = $('<span class=\"'+$(element).attr('class')+'\" style=\"visibility:hidden;\">'+$(element).val()+'</span>');
$(document.body).append(span);
var diff = $(element).width() - $(span).width();
$(span).remove();
return diff;
}
One way to do it is creating a span element and adding your text to it. But there is a catch: you have to add it to the dom in order get its with:
var sYourText = 'asdfafdsa, dzcvxvxc';
var oText = document.createElement('span');
oText.innerHTML = sYourText;
document.getElementsByTagName('body')[0].appendChild(oText)
console.log(oText.offsetWidth);
Of course: be sure to apply the same font that your textarea have.
$("textarea").keyup(function(){
var s = $(this).val()
var data = s.replace(/(\s)/g,' ')
console.log(data)
$('span').html(data)
})
I replace it with a regular spaces replaced, but wrapping problems that may require using CSS

how to select a text range in CKEDITOR programatically?

Problem:
I have a CKEditor instance in my javascript:
var editor = CKEDITOR.instances["id_corpo"];
and I need to insert some text programatically, and select some text range afterwards.
I already did insert text through
editor.insertHtml('<h1 id="myheader">This is a foobar header</h1>');
But I need to select (highlight) the word "foobar", programatically through javascript, so that I can use selenium to work out some functional tests with my CKEditor plugins.
UPDATE 1:
I've also tried something like
var selection = editor.getSelection();
var childs = editor.document.getElementsByTag("p");
selection.selectElement(childs);
But doesn't work at all!
How can I do that?
I think that
selection.selectRange()
could do the job, but I'could not figure out how to use it.
There are no examples over there :(
Get current selection
var editor = CKEDITOR.instances["id_corpo"];
var sel = editor.getSelection();
Change the selection to the current element
var element = sel.getStartElement();
sel.selectElement(element);
Move the range to the text you would like to select
var findString = 'foobar';
var ranges = editor.getSelection().getRanges();
var startIndex = element.getHtml().indexOf(findString);
if (startIndex != -1) {
ranges[0].setStart(element.getFirst(), startIndex);
ranges[0].setEnd(element.getFirst(), startIndex + findString.length);
sel.selectRanges([ranges[0]]);
}
You can also do the following:
get the current selection
var selection = editor.getSelection();
var selectedElement = selection.getSelectedElement();
if nothing is selected then create a new paragraph element
if (!selectedElement)
selectedElement = new CKEDITOR.dom.element('p');
Insert your content into the element
selectedElement.setHtml(someHtml);
If needed, insert your element into the DOM (it will be inserted into the current position)
editor.insertElement(selectedElement);
and then just select it
selection.selectElement(selectedElement);
Check out the selectElement() method of CKEDITOR.dom.selection.
http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.dom.selection.html
insert text at cursor point in ck editor
function insertVar(myValue) {
CKEDITOR.instances['editor1'].fire( 'insertText',myValue);
}
this is working for me

Categories

Resources