I am building a classic post related cms on LAMP stack, as a project to show at future interviews and land a job potentially. I want to build a rich text editor. After some research both in r/javascript and stack overflow I drew some conclusions.
Don't use "contentEditable=true" flag because according to one of
CKEditor's devs https://stackoverflow.com/a/11479435/10245890 is not optimal
The general consensus is to use iframe because of the isolation it
provides.
Yes I know I will not build the next CKEditor on my own, it takes
years of far more experienced people than me, I just want to learn
about the Javascript APIs.
Generally I want to use vanilla version of the languages in the
stack in order to get a better understanding of them.
The 'easy' way out to get a simple rich text editor going is to use execCommand but it is obselete. What I came up with goes like this:
function formatBold(){
var selection = document.getSelection().toString();
var originalString = document.getElementById("post-body-editor").innerHTML;
document.getElementById("post-body-editor").focus();
document.getElementById("post-body-editor").innerHTML = originalString.replace(selection, '<b>'+ selection +'</b>');
return;
}
document.addEventListener('keydown', function(event) {
if(event.ctrlKey && event.key === 'b'){
formatBold();
return;
}
return;
});
The function is called with a HTML button or key press. I saw in MDN that there is a method to implement insert Link, format a text with bold etc. Question is. I see some, if not many ,methods flagged as deprecated but they seem to be working. Should I use them or make it work on my own as shown above? I realize its not the most elegant solution but I believe it works fine for my level. Also any articles or other reading material is appreciated ofc.
EDIT:Formatting
If the question is just about using deprecated/obsolete features, the answer is: don't use. Though, I doubt execCommand would never really be removed from the browsers, that would break tons of existing pages ... If you really want to create a WYSIWYG editor, you've to dive deep in the world of DOM. In that world use of innerHTML is exceptional, you would work with Nodes and ShadowRoot etc.
Answered by Teemu in comment above.
Related
UPDATE: even though I've put a bounty here, the answers provided are not even slightly helpful so save yourself the time and move on... sorry.
My URL is: http://colnect.com/en/forum/viewtopic!f%3D46%26t%3D35678
Click the "Translate" button offered by Google. This used to work just fine. Now it translates some of the blocks and for others shows only > instead of translation or keeping the original. I've attached here an "after" screen captures. If you follow the URL and try it for yourself you'll see more parts were being removed. Perhaps Google changed something in the way the button works or there's some Javascript bug there. Would be happy for any ideas here. Thanks
Note: cross-posted on http://productforums.google.com/forum/#!category-topic/webmasters/internationalization/rykImZlToVk
Not quite sure what this has to do w/ programming (if you're a developer for the site, making a browser plugin, etc.), but if I had to purpose a way that translation is being buggy I'd suggest these things:
Check that elements on the website's page are properly identified. No dead links, misroutings, wrongful JavaScript element calls, wrongful CSS element declarations, etc.
Check that the Google Translate API is set up correctly. If everything is working fine on Google Translate itself, everything should be fine w/ the core API.
The solution may be found in one of the suggestions on that topic's fourth page, first post:
I support option 1 ("Translate" icon for each individual post). I think it will be very convenient -
1/ Usually you are interested in a translation of only a few posts out of every page at most anyway. There is no need to translate the whole page.
2/ It will be possible to translate different posts in different languages in the same page.
3/ No need to scroll up the page to click "Translate"
4/ Will be able to see original text
What I'm believing is that, due to the nature of your fora, the translator assumes that an individual post is one language and will try to back-translate it to the user's preferred. What happens is actually evident in the (current) translator for the first post.
I would like to inform you that in the box no longer works the translator.
Let me know if you too have experienced the inconvenience.
thanks
becomes
I would like to Inform You That in the box no longer works the translator.
Let me know if you too have experienced the inconvenience.
thanks
with an appended ,[lang code] at the end of the post.
By the way, you can see the picture's problem here despite the rest being in English and a post in Spanish. I'm assuming the translator is thinking every post is in Spanish (or whatever language it is) and it decides to spit garbage when it doesn't know how to translate to the preferred language.
As much as I love having multiple languages in a single post or even a forum topic, a machine translation cannot tell the difference between "A" language and "A" language despite being the same and being tagged as (in the example) Italian, Spanish, or what have you. This is an error in Google Translate, known as "recursive translation", and may not be fixed for a while.
So, what I recommend is this:
Ask your users to preferably write in one language. This is for the sake of the machine translation so that the poster doesn't confuse it.
Add a dedicated translate button to each post. Not only will this speed up times, it will be way more convenient as outlined by the poster, and avoid any errors not tagged with their respective [lang tag].
Unless this is not implemented (and I believe it is), it would be best to have your own tagging system so Google Translate will know the difference between "A" and "B" languages. In addition to this, you can also mess around with the site's code so that {some foreign language}[lang code] will be wrapped around the text. For example:
{Vorrei comunicare che nella casella posta non funziona più il traduttore.
Fatemi saper se avete anche voi riscontrato l'inconveniente.
Grazie}[it]
{Paulo}[dnt]
When implementing a web-based rich-text editor, I read that document.execCommand is useful for performing operations on an HTML document (like making a selection bold). However, I need something a bit better. Specifically, I need to know exactly what text is added or removed from the innerHTML, and in what location (as an offset into the entire document's HTML representation).
I considered using the built in document.execCommand along side DOM4's mutation observer, but execCommand doesn't seem up to the task:
I don't see a way to "un-bold" a selection
the generated html seems to vary from browser to browser. (I'd like < span > tags not < b >, but consistency is more important)
and there's no information on what it does to handle redundantly nested/adjacent < span > tags.
Also, using mutation observer seems a bit overkill based on my needs.
My motivation: I'm trying to transmit document changes to the server periodically without re-transmitting the whole document. I'm sending the data as a collection of insertions and deletions upon the HTML representation. If someone knows a way to get this functionality out of, say, CKEditor (so I don't have to start from scratch), then I would love you forever.
Note: Performing a text diff is not an option, due to its poor performance on very large documents.
Otherwise, I'm not exactly afraid of trying to write something that does this. The methods provided by the DOM's range object would handle a lot of the heavy lifting. I'd also appreciate advice regarding this possibility.
There is one alternative to using execCommand - implementing the whole interaction of an editor including blinking of a cursor. And it has been done. Google does it in docs, but there's something free and open-source too. Cloud9 IDE http://c9.io has an implementation.
AFAIK, github uses that editor for some time now. And you surely can do anything under that, because there's no native code involved - like in execCommand
The repo is here: https://github.com/ajaxorg/cloud9 (it contains the whole IDE, you will need to find the code for the editor. )
Also - dom mutation events are deprecated. If you can drop support for old browsers, try mutation observer. If not - try to avoid detecting DOM changes at all and intercept changes in the editor's implementation. It might be the way to go for the new browsers too.
There is Trix rich text editor, from their description it looks like avoiding inconsistent execCommand is the whole point of the project.
It seems the new standard will be Input Events Level 2. To me it looks like it will be a revised improved version of execCommand.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to create a WYSIWYG editor using a div, just like Google Docs works (as far as I know). I am aware there are other, easier solution for editors, but all have one thing in common: they output terrible HTML thanks to the Javascript execCommand() function. I really need it to output clean HTML (and the same HTML across browsers), so therefore I'm thinking about writing my own editor with a regular div and some Javascript (to record click and keypresses etc.) Before I do that though, I have a couple of questions:
Does the editor I'm looking for (one that outputs the same, clean HTML across browsers) already exist?
Am I mistaken that it is possible to write this?
Thanks a lot!
Edit: I think I should have been clearer on this: I don't consider existing WYSIWYG editors (like TinyMCE or CKEditor) an option, because (and please correct me if I'm wrong) they use the Javascript execCommand() function. This (especially in combination with an iFrame in design mode, which they both use), outputs different, illogical HTML in different browsers. For example: a simple enter in Safari causes it to create a div, instead of adding a <br /> tag or create a new paragraph (<p>). Furthermore: making text bold causes Mozilla to add <span style="font-weight: bold">, Internet Explorer and Opera to add <strong> and Safari to add a <b> tag. Not to mention the tricks some browsers pull by adding their name to tags (Safari I'm looking at you, I don't like <span class="Apple-style-span">). Because there's no way to change all these strange behaviors, it's very hard for me to make the site look consistent.
That's the reason I'm thinking about writing my own alternative: cross-browser compatibility and consistency...
Creating an editor from scratch is a massive undertaking because of the sheer number of browser quirks and bugs with in-browser editing. I've done it several times for various niche projects. My advice would be to start with either TinyMCE or CKEditor as a base and extend them. Both have had unbelievable amounts of development time poured into them over several iterations to get them as good as they are now. Try taking a look at their bug trackers to get an idea of what they have to contend with. Both have decent options for extension, so you could write your own formatting commands to replace document.execCommand() and in both you can add buttons/tools to the toolbar and context menus.
Self-promotion alert: Another option for the future is to use the commands module I'm working on for my Rangy library. It's some way off completion but will initially have replacements for inline formatting commands offered by document.execCommand(), and will allow control of the tags/CSS it produces. Rough early demo here: http://rangy.googlecode.com/svn/branches/1point2/demos/commands.html
Don't do this. There are teams of developers behind high profile WYSIWYG editors, and they already have the workflow built into their development to handle cross browser testing.
Look at
TinyMCE
CKeditor
Dojo Toolkit's Dijit.Editor
http://280slides.com/ built for the canvas tag
Everything is possible if you are stubborn enough.
The two we looked at were:
http://tinymce.moxiecode.com/
and
http://ckeditor.com/
Both did exactly what we wanted but in the end we went with the commercial CKeditor.
Did you already try TinyMCE ?
You have full control over the output via different parameters or existing plugins, also possible to write your own plugin..
On one of my sites, I used liberally to provide better hyphenation in the web browser. Unfortunately, they get corrupted by copying or cutting and pasting, so when people copy from my website, the ar-tic-les ap-pear with ex-tra hy-phens which are really annoying. I exaggerated it a bit here, but you get the idea.
I'd love a way to filter the selection on copy - basically an opportunity to remove the 's before they get to the clipboard. I suspect this isn't possible, based on what I've read/researched, but thought I'd ask the collective wisdom here, in case I've missed something.
A pseudocode example of what would be beautiful:
element.oncopy = function (ev) {
ev.selection.replace(//g, '');
return true; // or ev, I suppose
}
Have a look at this article about the oncopy event. I think it is exactly what you need: http://help.dottoro.com/ljwexqxl.php.
Example #2 on the following page explains how to use the clipboard in a cross-browser friendly way (since only IE has access to the clipboardData object used in the first article): http://help.dottoro.com/ljxundda.php
That page also mentions that there are some cases where security restrictions may prevent the cross-browser method from working, which is why some sites use Flash to manipulate the clipboard. Here's an article which discusses that method, in case it sounds like what you want: http://www.jeffothy.com/weblog/clipboard-copy/
EDIT
Have a look at Hyphenator.js. It is a JavaScript method of hyphenating text intelligently on the client side. Quickly playing around with the demo (which can be found here), it appears to leave the hyphens out of copied text. It might be a pain to change your content to use this instead of , but it looks like it will achieve all of your goals.
I need to make a comment mechanism in which user highlights a piece of text, clicks "comment this", and then does something. The Javascript code has to know not only the selected text (this is trivial), but also the anchorOffset, to know exactly from which to which character the text was selected.
I've found a cross-browser solution that gives you the text. Is there a reliable way to get a selection object as it's described in DOM specs?
You could try IERange, which creates a selection-like object in IE and adds a getSelection() method to window. I don't think it's perfect but it's about the best standalone Range/selection library there is that I've seen.
Update
I've been working on a Range/selection library called Rangy that goes beyond what IERange provides. There's an early release available at http://code.google.com/p/rangy.