Translate user selected text with Google Translate API (and jQuery) - javascript

I am working on some JavaScript for a website with content in multiple languages. I would like to use the Google Translate API to allow the user to select a word (or phrase) and have a translation automatically provided. For the time being, I'm simply having it alert the result for testing.
This is what I have so far:
google.load("language", "1");
function getSelection() {
var selection = (!!document.getSelection) ? document.getSelection() :
(!!window.getSelection) ? window.getSelection() :
document.selection.createRange().text;
if (selection.text)
selection = selection.text
console.log(selection);
return selection
}
$(document).ready(function() {
$(window).mouseup(function() {
var selection = getSelection();
if (selection != "") {
google.language.translate(selection, "", "en", function(result) {
if (!result.error) {
alert(result.translation);
} else {
alert(result.error);
}
});
}
});
});
The problem that I'm running into is that my getSelection() function is returning a Range objects, which is apparently incompatible with google's language.translate() function. All I really need is a way to retrieve the actual text from the Range as a string so I can pass that. As far as I know there's some really easy, obvious way to do this that I'm just missing (yes, I tried using selection.text), but my experience with JavaScript is limited and Googling it hasn't revealed anything useful.
Can anyone help?

Try jQuery google translate - http://code.google.com/p/jquery-translate/.

Unsurprisingly there was a really obvious answer that I just completely missed. selection.toString()...

You can do something like this:
function getSelection() {
var selection = window.getSelection ? window.getSelection() + ''
: document.selection.createRange().text;
return selection
}
By concatenating an empty string to the result of the getSelection() method, its value gets converted to string, it's a common short-hand, equivalent to call the toString method, because:
var test = {
toString: function () {
return 'foo';
}
};
test+'' == 'foo'; // true
You also don't need to use the double logical negation (!!) in a ternary, because the first operand, the condition, its automatically converted to Boolean.

Related

How to convert a Char by the position on the keyboard?

I need a way to convert the a string, or a char, to it's equivalent on the keyboard on a different language. and as such, in hebrew, for example, "ש" will become "a" or "A".
Couldn't find the proper way to do so without creating a giant switch statement or a dictionary.
any answer on either JS or C# will be great.
Use keyCode of the keydown or keyup events. Property of this event contains code of keyboard key but not code of symbol.
document.addEventListener("keyup", function(event){
console.log(String.fromCharCode(event.keyCode));
});
here is how i do it in javascript
qwerty_mapping = {
"ת":"," ,",":"ת"
,"ף":";" ,";":"ף"
,"ץ":"." ,".":"ץ"
,"ש":"a" ,"a":"ש"
,"נ":"b" ,"b":"נ"
,"ב":"c" ,"c":"ב"
,"ג":"d" ,"d":"ג"
,"ק":"e" ,"e":"ק"
,"כ":"f" ,"f":"כ"
,"ע":"g" ,"g":"ע"
,"י":"h" ,"h":"י"
,"ן":"i" ,"i":"ן"
,"ח":"j" ,"j":"ח"
,"ל":"k" ,"k":"ל"
,"ך":"l" ,"l":"ך"
,"צ":"m" ,"m":"צ"
,"מ":"n" ,"n":"מ"
,"ם":"o" ,"o":"ם"
,"פ":"p" ,"p":"פ"
,"/":"q" ,"q":"/"
,"ר":"r" ,"r":"ר"
,"ד":"s" ,"s":"ד"
,"א":"t" ,"t":"א"
,"ו":"u" ,"u":"ו"
,"ה":"v" ,"v":"ה"
,"'":"w" ,"w":"'"
,"ס":"x" ,"x":"ס"
,"ט":"y" ,"y":"ט"
}
function correctChar(old_char){
if(qwerty_mapping[old_char] == undefined)
{
return(old_char)
}
else
{
return(qwerty_mapping[old_char])
}
}
function correctString(old_string){
new_string = ""
for(i=0;i<old_string.length;i++){
new_string = new_string+correctChar(old_string[i])
}
return new_string;
}
in case someone will look for this answer, It seems like that isn't a clear way of doing that without using a dictionary or a switch statement.
basa.

How to remap keyboard within the same textarea

Currently i am doing a project with remapping characters to words by detecting the keyup function. Unfortunately, i have only been able to retrieve the first character and remap to the word i want. In my project, i need to directly retrieve all of my keyboard input and directly convert it to the word that i want within the same textarea. For example when i type in the textarea, it will convert to "are" directly. I don't know why it stopped retrieving the second character and remapping not function. Below is my code, hope someone can tell me my error. Thank you.
<textarea class="width-100" id="translated-text" onkeyup="myFunctionkey(event);" rows="10"></textarea>
<script>
function myFunctionkey(e) {
conversion();
}
function conversion(){
var x = document.getElementById('translated-text');
if(x.value == 'a'){
x.value='yes';
}
if(x.value == 'q'){
x.value = 'are';
}
}
</script>
From what I understand, you only want to grab the input and replace a key stroke with a complete word.
Maybe this will do. I've changed onkeyup to onkeypress because this is more reliable from what I remember.
<textarea id="translated-text" cols="50" rows="10" onkeypress="replaceInputChar(event);"></textarea>
<script type="text/javascript">
//create replacement map
var map = {
"a": "and",
"b": "bold",
"c": "change"
};
function replaceInputChar(e)
{
var ctl = document.getElementById("translated-text"); //control
var char = String.fromCharCode(e.keyCode); //typed char
if (char in map) //check if letter is defined in map
{
//insert replacement instead of letter
if("selectionStart" in ctl)
{
//in modern browsers we can easily mimic default behavior at cursor position
var pos = ctl.selectionStart;
ctl.value = ctl.value.substr(0, pos) + map[char] + ctl.value.substr(ctl.selectionEnd);
ctl.selectionStart = pos + map[char].length;
ctl.selectionEnd = ctl.selectionStart;
}
else
ctl.value += map[char];
if ("preventDefault" in e) //modern browser event cancelling
e.preventDefault();
else
{
//old browser event cancelling
e.returnValue = false; //IE8
return false;
}
}
}
</script>
You should use comparison operator '==' instead of assignment operator '=' while remapping the value, like this:
x.value=='a'
Edit:
You should check the updated code for your problem here:
https://jsfiddle.net/o4coLr5t/1/
Now, the characters you choose to remap in javascript will display the string, that you map the character to. Otherwise it will display nothing on pressing keys. So, try and add all the character keycodes to the javascript code. Hope that helps.

Check if input fields contains certain text

I'm trying to find if what the user typing in to an input field contain certain text - I've kinda got it works, but only working for an exact match as opposed to a partial match. If a user types anything before the text i'm matching, of course the code doesn't trigger.
What i need to do is check if the input contains #nyu.edu at all in the input field.
$('.email').keyup(function(){
if ($(".email").val() == "#nyu.edu") {
$("p.warning").css("visibility", "visible");
}
else if ($(".email").val() != "#nyu.edu") {
$("p.warning").css("visibility", "hidden");
}
});
Checking if a string contains a substring is pretty easily done by taking haystack.indexOf(needle) and checking against -1 (not found).
if ($(".email").val().indexOf("#nyu.edu") !== -1) {
// contains
} else {
// does not contain
}
There is a function in the ES6 draft which you may find more natural, called includes
You can add support for ES6's String.prototype.includes like this
if (!String.prototype.includes) {
String.prototype.includes = function (needle, pos) {
return this.indexOf(needle, pos || 0) !== -1;
};
}
"foobar".includes('foo'); // true
Working Ex:
http://codepen.io/anon/pen/XJKMjo
$('.email').keyup(function() {
var exp = /#nyu\.edu$/; // reg ex
var input = $(this).val(); // email input
var matches = exp.test(input); // boolean
// changes to hidden or visible
$("p.warning").css("visibility", (matches) ? "visible" : "hidden");
});
You can filter based on HTML elements' attribute contents with jQuery to either contain, start, or end with a string that you want. To match elements with an attribute that contain a string, you'd use [attr*="value"] in your jQuery selector, but I think that you want something where the end matches your string. Here's how that would work:
var elements = $(".email[value$='#nyu.edu']");
if(elements.length > 0) {
// Do something with the elements, such as removing an .error class
} else {
// Email doesn't end with #nyu.edu
}
Read more about the jQuery ends-with attribute selector or browse through other attribute selectors like this.
jsBin demo
var $warning = $("p.warning"); // P.S. make sure not to target a wrong .warning!
$('.email').on("input", function(){
$warning.toggle( /#nyu\.edu/ig.test(this.value) );
});
as I've mentioned .warning being a class can represent any first .warning occurrence. use rather some other selector like .next() or .closest(selector).find(".warning")
your boss fill fire you if your client loses $$$ cause you forgot to watch for copy-paste cases. ;) Kidding, use "input" event.
P.S use .warning{display:none;} instead of visibility

is it possible to check the XMLHttpRequestObject.responseText value using if condition

Is it possible to check the XMLHttpRequestObject.responseText value using if condition instead of just displaying it?
I have tried like this.
var a=XMLHttpRequestObject.responseText;
if(a=="false")
{
document.getElementById("show_mark").innerHTML =a;
}
I know its wrong,but i need to do like this.Is there any other alternative way for doing this?Help me i am completely a newbie to AJAX.
It is possible that the response text has added white spaces. To remove white spaces at the start and end of a string use string.trim().
In your case a=a.trim()
If trim is not available in your browser's JavaScript interpreter add in
if (!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g, '');
};
}
Source
Finally i found the mistake.Its not the white spaces around the value.Actually its all the html tags like <html><body>false</body> etc., I removed these characters with the help of this code. I got the answer.
var a=XMLHttpRequestObject.responseText;
a = a.replace(/&(lt|gt);/g, function (strMatch, p1){
return (p1 == "lt")? "<" : ">";
});
var b = (a.replace(/<\/?[^>]+(>|$)/g, "")).trim();
if(b=="false")
{
document.getElementById("show_mark").innerHTML =b;
}
Thanks for the support.

Convert HTML Character Entities back to regular text using javascript

the questions says it all :)
eg. we have >, we need > using only javascript
Update: It seems jquery is the easy way out. But, it would be nice to have a lightweight solution. More like a function which is capable to do this by itself.
You could do something like this:
String.prototype.decodeHTML = function() {
var map = {"gt":">" /* , … */};
return this.replace(/&(#(?:x[0-9a-f]+|\d+)|[a-z]+);?/gi, function($0, $1) {
if ($1[0] === "#") {
return String.fromCharCode($1[1].toLowerCase() === "x" ? parseInt($1.substr(2), 16) : parseInt($1.substr(1), 10));
} else {
return map.hasOwnProperty($1) ? map[$1] : $0;
}
});
};
function decodeEntities(s){
var str, temp= document.createElement('p');
temp.innerHTML= s;
str= temp.textContent || temp.innerText;
temp=null;
return str;
}
alert(decodeEntities('<'))
/* returned value: (String)
<
*/
I know there are libraries out there, but here are a couple of solutions for browsers. These work well when placing html entity data strings into human editable areas where you want the characters to be shown, such as textarea's or input[type=text].
I add this answer as I have to support older versions of IE and I feel that it wraps up a few days worth of research and testing. I hope somebody finds this useful.
First this is for more modern browsers using jQuery, Please note that this should NOT be used if you have to support versions of IE before 10 (7, 8, or 9) as it will strip out the newlines leaving you with just one long line of text.
if (!String.prototype.HTMLDecode) {
String.prototype.HTMLDecode = function () {
var str = this.toString(),
$decoderEl = $('<textarea />');
str = $decoderEl.html(str)
.text()
.replace(/<br((\/)|( \/))?>/gi, "\r\n");
$decoderEl.remove();
return str;
};
}
This next one is based on kennebec's work above, with some differences which are mostly for the sake of older IE versions. This does not require jQuery, but does still require a browser.
if (!String.prototype.HTMLDecode) {
String.prototype.HTMLDecode = function () {
var str = this.toString(),
//Create an element for decoding
decoderEl = document.createElement('p');
//Bail if empty, otherwise IE7 will return undefined when
//OR-ing the 2 empty strings from innerText and textContent
if (str.length == 0) {
return str;
}
//convert newlines to <br's> to save them
str = str.replace(/((\r\n)|(\r)|(\n))/gi, " <br/>");
decoderEl.innerHTML = str;
/*
We use innerText first as IE strips newlines out with textContent.
There is said to be a performance hit for this, but sometimes
correctness of data (keeping newlines) must take precedence.
*/
str = decoderEl.innerText || decoderEl.textContent;
//clean up the decoding element
decoderEl = null;
//replace back in the newlines
return str.replace(/<br((\/)|( \/))?>/gi, "\r\n");
};
}
/*
Usage:
var str = ">";
return str.HTMLDecode();
returned value:
(String) >
*/
Here is a "class" for decoding whole HTML document.
HTMLDecoder = {
tempElement: document.createElement('span'),
decode: function(html) {
var _self = this;
html.replace(/&(#(?:x[0-9a-f]+|\d+)|[a-z]+);/gi,
function(str) {
_self.tempElement.innerHTML= str;
str = _self.tempElement.textContent || _self.tempElement.innerText;
return str;
}
);
}
}
Note that I used Gumbo's regexp for catching entities but for fully valid HTML documents (or XHTML) you could simpy use /&[^;]+;/g.
There is nothing built in, but there are many libraries that have been written to do this.
Here is one.
And here one that is a jQuery plugin.

Categories

Resources