Hello,
While I was working on a project that I released last night I did many things and custom commands for CKEditor. Out of those I am sharing a couple of lines code with you which will show you how to get selected text from CHEditor and how to perform an operation on the returned text.
Ok so first of all we do our usual stuff and transform our textarea to a Rich text editor.
A simple one liner I guess
1 |
<textarea class="ckeditor" id="my_editor"></textarea> |
1 |
Note that the class ckeditor is intentional and when you include ckeditor.js on your page that will do the trick and transform you simple editor to a Rich text editor. Ok so now considering that all went well, lets get hold of instance of our editor as shown below
1 |
var editor = CKEDITOR.instances.my_editor; |
That was pretty simple. I used DOT notation but you can also get editor instance in typical array value retrieval though keys too as shown below
1 2 |
// var editor = CKEDITOR.instances["my_editor"]; // please note that my_editor is unique ID of our text area |
Alright! now that we have our editor instance lets do couple of things. To start with lets add couple of buttons to our page as shown below
1 2 |
<input type="button" value="To Uppercase" onclick="uppercase()"> <input type="button" value="To Lowercase" onclick="lowercase()"> |
One of the button is calling our yet to be declared javascript function uppercase() and second calling lowercase()
Lets declare these functions as shown below
Our uppercase function
1 2 3 4 5 |
function uppercase() { // please note that editor variable that we declared earlier should come before this code. var selection = editor.getSelection(); if(selection) {editor.insertHtml("<p>"+selection.getSelectedText().toUpperCase()+"</p>"); } } |
Our lowercase function
1 2 3 4 5 6 7 |
function lowercase() { // please note that editor variable that we declared earlier should come before this code. var selection = editor.getSelection(); if(selection) { editor.insertHtml("<p>"+selection.getSelectedText().toLowerCase()+"</p>"); } } |
That’s it. Try it and I am pretty sure that you will get it right the first time.
Demo
I’ll add a demo when I get a chance.
Please note: You can also write custom command to do exactly the same stuff but I’ll leave that exercise to you.
I hope this helps and gives you a pointer to achieve a solution. If you have anything to add please leave your comment.
Cheers.
thanks so much I spend all the day lock for that.
There is a ready to use plugin that accomplish what you are looking for:
http://ckeditor.com/forums/Plugins/Text-Transform-plugin-for-CKeditor