How detect actual language of webpage translated via Google translate? - javascript

I need to detect the translated language and ideally make some class maybe to body. After that via this class edit CSS of webpage. I have no problem with solutions with jQuery or pure JavaScript.
I need this because different languages has different length of words and this can make me problem with design. I need solved this like
.language_cz .some_class{
font-size: 14px;
}
.language_en .some_class{
font-size: 16px;
}
I make this translate via https://gtranslate.io/. This is pure Google translate.
Code of translate is:
<div class="obal_mutace">
<span class="aktualni_mutace">CZ</span>
<div class="blok_mutace_in">
<span data-id="CZ" class="polozka_mutace_in">CZ</span>
<span data-id="EN" class="polozka_mutace_in">EN</span>
<span data-id="DE" class="polozka_mutace_in">DE</span>
<span data-id="RU" class="polozka_mutace_in">RU</span>
<span data-id="FR" class="polozka_mutace_in">FR</span>
<span data-id="IT" class="polozka_mutace_in">IT</span>
<span data-id="PT" class="polozka_mutace_in">PT</span>
<span data-id="ES" class="polozka_mutace_in">ES</span>
<div id="google_translate_element2"></div>
<script type="text/javascript" src="funkce/transl_init.js?v=1.0.1"></script>
<script type="text/javascript" src="http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit2"></script>
</div>
in "transl_init.js" I have:
function googleTranslateElementInit2() {new google.translate.TranslateElement({pageLanguage: 'cs',autoDisplay: false}, 'google_translate_element2');}
/* <![CDATA[ */
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('6 7(a,b){n{4(2.9){3 c=2.9("o");c.p(b,f,f);a.q(c)}g{3 c=2.r();a.s(\'t\'+b,c)}}u(e){}}6 h(a){4(a.8)a=a.8;4(a==\'\')v;3 b=a.w(\'|\')[1];3 c;3 d=2.x(\'y\');z(3 i=0;i<d.5;i++)4(d[i].A==\'B-C-D\')c=d[i];4(2.j(\'k\')==E||2.j(\'k\').l.5==0||c.5==0||c.l.5==0){F(6(){h(a)},G)}g{c.8=b;7(c,\'m\');7(c,\'m\')}}',43,43,'||document|var|if|length|function|GTranslateFireEvent|value|createEvent||||||true|else|doGTranslate||getElementById|google_translate_element2|innerHTML|change|try|HTMLEvents|initEvent|dispatchEvent|createEventObject|fireEvent|on|catch|return|split|getElementsByTagName|select|for|className|goog|te|combo|null|setTimeout|500'.split('|'),0,{}))
/* ]]> */
I used it on my webpage project http://www.kalimera-recko.cz/. I used Google translate in head of web on the left from search input.

If I understand your question correct you want to style your page according to the used language.
On your page you set the language attribute on the html tag.
<html class="js" style="height: 100%;" lang="cs">
So you can address it in your css with this:
html[lang="cs"] .some_class
[EDIT]__________________
A cookie is set
"googtrans" to the value /cs/en if translated to englisch and to te value /cs/de if translated to german.
You can find out the value of the cookie with javascript or jQuery
document.cookie
It returns a string where you need to search for the "googtrans" value.
You can get the language with this:
var cookie = document.cookie;
var position = cookie.indexOf("googtrans");
var language = cookie.substring(position+10, position + 16);
This code can be optimized if you search for the end of the value ';' instead of using fixed numbers.
But this will do what you need.
You may also should use a try/catch and see if the cookie exists because it doesn't exist for your original language.

Related

Changing language with toggle button bootstrap

I'm learning to code with bootstrap, html, css, js. And I'm wondering if it's possible to modify the language of my webpage with a toggle button?
I'm using bootstrap toggle which can set events like this:
<input id="toggle-event" type="checkbox" data-toggle="toggle">
<div id="console-event"></div>
<script>
$(function() {
$('#toggle-event').change(function() {
$('#console-event').html('Toggle: ' + $(this).prop('checked'))
})
})
</script>
And I also saw this thread on stack about changing languageusing element.lang.
And I'm not able to 'mix' the two methods to change the language on deman simply by clicking on the toggle button, and I don't understand why =/
Here's my attempt:
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/bootstrap-toggle.min.js"></script>
<body class="fr" id="test1">
<p lang="en">
Je parle la baguette
</p>
<p lang="fr">
I speak the baguette
</p>
<input id="toggle-event" type="checkbox" checked data-toggle="toggle" data-size="large" data-onstyle="info" data-offstyle="info" data-on="Fr" data-off="En">
<!--<script>
$(function() {
$('#toggle-event').bootstrapToggle({
on: document.body.className= 'fr',
off: document.body.className = 'en'
});
})
</script>-->
<script>
$(function() {
$('#toggle-event').change(function() {
$('#test1').body('Toggle: ' + $(this).prop('checked')).className='en'
});
});
</script>
</body>
CSS:
body.en :lang(en) {
display: none;
}
body.fr :lang(fr){
display: none;
}
https://jsfiddle.net/mttkchfc/1/
There are a number of issues with your attempt.
The most obvious one is that the languages are the wrong way round. Your "en" section contains French text, and the "fr" one contains English text!
The CSS is also mangled compared to the example you cited - look more carefully at how the :lang part is constructed in the original. In the original example, it is used to hide the opposite language, whereas you're using it to hide the same language. You've got the concept the wrong way round.
Also, this line is total nonsense:
$('#test1').body('Toggle: ' + $(this).prop('checked')).className='en'
There's no such jQuery function as ".body" - if you look in your browser console (press F12, if you didn't know, to open the Developer Tools in most modern desktop browsers), you'll see this error reported when you click on the toggle.
"classname" is a native JS property, it doesn't work on jQuery objects, which this would be if it was valid
If it was possible to use a function like "body" to set the body content, all it would do is set the content of the whole <body> section to "Toggle: true", or similar. This would be useless.
Even if all of that were to be ignored, and it were capable of setting the class, it only ever sets it to English - you wouldn't be able to change back to French.
The example in the link you gave, using document.body.className works perfectly well. You just need to vary the class name depending on whether the toggle is on or off. I have chosen to store the class names in data- attribute values "true" and "false", which of course correspond to the string representation of a boolean. This means we can neatly use the value of the "checked" property of the toggle to fetch the correct data- attribute value and use that as the new class name, without any tedious if or switch statements:
CSS
body.en :lang(fr) {
display: none;
}
body.fr :lang(en){
display: none;
}
HTML
<body class="en">
<p lang="fr">
Je parle la baguette
</p>
<p lang="en">
I speak the baguette
</p>
<input id="toggle-event" type="checkbox" checked data-toggle="toggle" data-size="large" data-onstyle="info" data-offstyle="info" data-on="English" data-off="French" data-true="en" data-false="fr" >
</body>
JS
$(function() {
$('#toggle-event').change(function() {
document.body.className = $(this).data($(this).prop("checked").toString());
});
});
P.S. Your JSFiddle didn't work at all because you didn't include jQuery, your scripts were in the wrong section, and you have to reference bootstrap etc as external resources - the inline links you provided were pointing to local resources which don't exist in a JSFiddle environment. I've fixed that for you, plus updated it so it works as you intend:
https://jsfiddle.net/mttkchfc/4/

html Multilingual website - Language latency occurring

I'm implementing a multilingual solution on my website : I detect the browser language of the user.
What I have in the HTML is the default text in English.
All the text objects are being assigned an id.
Then in a JS sheet I use innerHTML to replace the text in the correct language, to translate into French.
HTML
<div>
<h3 id="test">
This is a Test !
</h3>
</div>
JS
function adjust_languages() {
// change all object text, if french
if (sprache == "french") {
document.getElementById("test").innerHTML = "Ceci est un test !";
}
This works quite well. However, when the user's connection is not very fast, a latency occurs between the moment when the HTML text is displayed in English and the moment when it gets translated into French.
In other words, the user sees English for let's say 1 second, before it gets translated into French.
I was thinking of getting rid completely of text in the HTML and have the English language in the JS as well, but that would mean 0 text in the HTML file, which I think is not very usual...
What would be your advice to have the right language displayed at first, without any latency occurring ? Many thanks for your help.
I think you should make a text box on what language you want.
<!DOCTYPE html>
<html>
<head>
<title>Langtest</title>
</head>
<body>
<input type="text" id="lang" placeholder="Type a language">
<button onclick="adjust_languages()">Change!</button>
<h3 id="test">This is a test!</h3>
</body>
<script>
var sprache = document.getElementById("lang").textContent;
function adjust_languages()
{
if (sprache = "french")
{
document.getElementById("test").innerHTML = "Ceci est un test !";
}
}
</script>
</html>
Think you must need a var so no lag will happen even you have slow connection and do not use external APIs
Either translate on the server or use a client template library to translate on the client. I'd recommend mustache because it's very simple to use and lightweight. It'll make your life easier and it might run faster than your own solution.
Also if you don't want to do that anyway: use textContent instead of innerHTML. The latter needs to determine if the content is HTML or not and evaluate any element it finds while textContent just creates a text node with the string in it.

Are they any syntax highlighting plugins that will allow you to embed an ignorable html element into a snippet?

I am trying to make dynamic code examples for our api that can be constructed from from input html elements.
A paired down example looks like this, I give the user an input to name the device they would like to create.
<input class="observable-input" data-key="deviceName" type="text" value="deviceKey" />
I would then like that input to update code examples (replacing the device name in the example with the one the user inputs).
<code lang="python">
device = { "name": "<span data-observeKey="deviceName">Name</span>" }
client.createDevicewrite(device)
</code>
I have all of the code setup for observing a change in the input and updating the code examples, this works great. All of the syntax highlighters I have looked at, usually chop the snippet up and rerender the example wrapped with its own html (for styling). Is there an option/configurable way to get a syntax highlighter to not strip the these tags, or is there a different approach I should be looking at for preserving the syntax highlighting and still supporting dynamic updates without having to do a full text search of each snippet's rendered tags.
The example output of the pygment (current syntax highlighter I'm using).
<li>
<div class="line">
<span class="n">device</span>
<span class="o">=</span>
<span class="n">{</span>
<span class="s">"name"</span>
<span class="p">:</span>
<span class="s">"Name"</span>
<span class="n">}</span>
</div>
</li>
I decided to just go with a brute force approach, it ended up being decently performant, ill leave my code here if anyone is interested in what I did
https://gist.github.com/selecsosi/5d41dae843b9dea4888f
Since i use backbone, lodash, and jquery as my base app frameworks the gist uses those. I have a manager which will push updates from inputs to spans on the page which I use to dynamically update the code examples

Loop to change content of href for many anchors

The content of my posts in Wordpress is a big markup. It is coming from MS Word so it is text wrapped by HTML nested tags and inline styles.
I have a segment of code that is repeated many times in the content (It represents text footnotes). This segment, for the first footnote for example is:
<sup><a title="" href="file:///C:/Users/hp/Desktop/file.docx#_ftn1" name="_f
tnref1">
<span class="MsoFootnoteReference">
<span dir="LTR">
<span class="MsoFootnoteReference">
<span lang="EN-US" style="font-size: 16pt; line-height: 115%;">
[1]
</span>
</span>
</span>
</span>
</a></sup>
.....
<a title="" href="file:///C:/Users/hp/Desktop/file.docx#_ftnref1" name="_ftn1">
<span class="MsoFootnoteReference">
<span dir="LTR" lang="EN-US" style="font-size: 12.0pt; font-family: 'Simplified Arabic','serif';">
<span class="MsoFootnoteReference">
<span lang="EN-US" style="font-size: 12pt; line-height: 115%;">
[1]
</span>
</span>
</span>
</span>
</a>
My goal is to change the 2 hrefs from:
href="file:///C:/Users/hp/Desktop/file.docx#_ftn1"
href="file:///C:/Users/hp/Desktop/file.docx#_ftnref1"
to:
href="#_ftn1"
href="#_ftnref1"
so that the user can jump from one anchor to the other.
Questions:
1- Is is better to use server side language instead of jquery?
2- How to loop over the repetitive segments and change the href contents of each couple of anchors?
Thank you very much in advance for your invaluable assistance.
Solution:
With the use of Regular expression provided by Broxzier + PHP, the code below is working and can be applied to any data before persisting it on the database.
if(preg_match_all('/href\s*=\s*"[^"]+(#[^"]+)"/',get_the_content(),$match))
{
echo preg_replace('/href\s*=\s*"[^"]+(#[^"]+)"/','href="$1"', get_the_content());
}
1- Is is better to use server side language instead of jquery?
Neither. The best and fastest option would be to totally remove the website and page name from the link if they're the same as the current page.
One way would be using Regular Expressions, this could be done via JavaScript, but I strongly suggest doing this by using a text editor and replace the old data (Wordpress saves revisions anyway).
The following regex will grab the href attribute
href\s*=\s*"[^"]+(#[^"]+)"
Replace this with:
href="\1"
And you're done.
2- How to loop over the repetitive segments and change the href contents of each couple of anchors?
Use a global flag to do this. Since it's content I advice you to do it manually or change the regex so that it will only match the current url.
Please note that this will also replace occurrences in the content, if there is any text like href="website#flag" in there. I assumed this was not the case.
--
Using jQuery.attr() and hash property of <a>
$('a').has('.MsoFootnoteReference').attr('href',function( idx,oldHref){
return this.hash;
});
You might want to use some html cleaning on your WYSIWYG html submissions that will clean out unwanted classes and modify the href's for you.
For example SimpleHtmlDOM php library uses css type selectors to modify html and you could use it to modify any href with file:// in it for example

How do you write Valid XHTML 1.0 Strict code when you are using javascript to fill an element that requires a child?

I'm running my site through the W3C's validator trying to get it to validate as XHTML 1.0 Strict and I've gotten down to a particularly sticky (at least in my experience) validation error. I'm including certain badges from various services in the site that provide their own API and code for inclusion on an external site. These badges use javascript (for the most part) to fill an element that you insert in the markup which requires a child. This means that in the end, perfectly valid markup is generated, but to the validator, all it sees is an incomplete parent-child tag which it then throws an error on.
As a caveat, I understand that I could complain to the services that their badges don't validate. Sans this, I assume that someone has validated their code while including badges like this, and that's what I'm interested in. Answers such as, 'Complain to Flickr about their badge' aren't going to help me much.
An additional caveat: I would prefer that as much as possible the markup remains semantic. I.E. Adding an empty li tag or tr-td pair to make it validate would be an undesirable solution, even though it may be necessary. If that's the only way it can be made to validate, oh well, but please lean answers towards semantic markup.
As an example:
<div id="twitter_div">
<h2>#Twitter</h2>
<ul id="twitter_update_list">
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&count=1"></script>
</ul>
</div>
Notice the ul tags wrapping the javascript. This eventually gets filled in with lis via the script, but to the validator it only sees the unpopulated ul.
Thanks in advance!
The following fragment is valid XHTML and does the job:
<div id="twitter_div">
<h2 class="twitter-title">Twitter Updates</h2>
<div id="myDiv" />
</div>
<script type="text/javascript">
var placeHolderNode = document.getElementById("myDiv");
var parentNode = placeHolderNode.parentNode;
var insertedNode = document.createElement("ul");
insertedNode .setAttribute("id", "twitter_update_list");
parentNode.insertBefore( insertedNode, placeHolderNode);
parentNode.remove(placeHolderNode);
</script>
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=twitterCallback2&count=5"></script>
Perhaps you could use javascript to write the initial badge HTML? You'd probably only want the badge code to be inserted in your document if javascript were available to populate it, right?
You'd just need to make sure your document writing happens before the javascript for your various badges.
Could you give a specific example of the HTML / link to a page with the invalid code?
The solutions might be different for each badge. In Twitter's case, you can just write your own callback function. Here's an example based on their badge code:
<div id="twitter_div">
<h2>#Twitter</h2>
<div id="twitter_update_list"></div>
</div>
<script type="text/javascript">
function updateTwitterCallback(obj)
{
var twitters = obj;
var statusHTML = "";
var username = "";
for (var i = 0; i < twitters.length; i++)
{
username = twitters[i].user.screen_name;
statusHTML += ('<li><span>' + twitters[i].text + '</span> <a style="font-size:85%" href="http://twitter.com/' + username + '/statuses/' + twitters[i].id + '">' + relative_time(twitters[i].created_at) + '</a></li>');
}
document.getElementById('twitter_update_list').innerHTML = '<ul>' + statusHTML + '</ul>';
}
</script>
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/stopsineman.json?callback=updateTwitterCallback&count=1"></script>
I put a <li> with "display:none" in the <ul> Tag:
<ul id="twitter_update_list"><li style="display:none;">A</li></ul>
<script type="text/javascript" src="http://twitter.com/javascripts/blogger.js"></script>
<script type="text/javascript" src="http://twitter.com/statuses/user_timeline/01241.json?callback=twitterCallback2&count=1"></script>
This does not disturb the script and in this case it works,
and I think its not a "undesirable solution" :)
At some point the page becomes valid, right? That's the only time it can really be validated.
I'm not sure a non-trivial page will remain valid at every point during its construction if it's constructed with a lot of DOM scripting.
This might not be the most popular opinion on this topic, but...
Don't worry about 100% validation. It's just not that big of a deal.
The point of validation is to make your markup as standard as possible. Why? Because browsers that are given markup that doesn't conform to the spec (eg, markup that does not validate) do their own error checking to correct it and display the page the way you intended it to look to the user. The quality of the browsers error checking varies, yadda-yadda-yadda, it's better to have valid markup... But it's not even your code that's causing the validation to fail! The people who wrote those badges probably tested them in multiple browsers (and you should do the same, of course), if they work as expected then just leave it at that.
In short, there's no prize for validating :)

Categories