I've successfully create javascript code to use Google AJAX Language API to translate plain text. Now I want to tranlate text in an instance of CKEditor, how to accomplish this?
First, I wouldn't recommend using the Google AJAX Language API, as it is deprecated as of December. You can use the Microsoft Translator instead, though the API isn't as nice.
Effectively, all you need to do is get the text from the editor, translate it, and stick it back in.
Get the text from the editor:
There's a bunch of different ways to do this, but you can use:
CKEDITOR.instances.editor1.getData()
Where editor1 is the ID of your editor. If you're using jQuery, you can do:
$('#editor1').val()
Translate it, and stick it back in:
This is as simple as calling the google API, and in the callback setting the editor's content:
google.language.translate(textToTranslate, translateFrom, translateTo, function(response) {
if (response.translation) {
CKEDITOR.instances.editor1.setData(response.translation);
}
});
or using jQuery:
google.language.translate(textToTranslate, translateFrom, translateTo, function(response) {
if (response.translation) {
$('#editor1').val(response.translation);
}
});
Put it all together into a function
var translate = function(editor, translateFrom, translateTo) {
var textToTranslate = editor.getData();
google.language.translate(textToTranslate, translateFrom, translateTo, function(response) {
if (response.translation) {
editor.setData(response.translation);
}
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With