html Multilingual website - Language latency occurring - javascript

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.

Related

Internationalization of a HTML + Markdown document (using RemarkJS)

I have many slides for a presentation made with RemarkJS. It is a HTML file slides_fr.html with a single <textarea id="source"> containing the actual content in Markdown syntax (+ one or two specific markup tags to separate the slides with a page break), and one call to the JS library RemarkJS.
I am translating this document into English (I first duplicated slides_fr.html into slides_en.html and started to translate). Problem: each time I do improvement on the slides in the English version, I'll have to remodify the original file slides_fr.html to keep them in sync. In my experience, this rarely works well on the long-term. It would be better to have both versions in the same file, with markup for language.
Question: in order to avoid having two files slides_fr.html and slides_en.html like this that will ultimately never stay in sync:
<html>
<head></head>
<body>
<textarea id="source">
First slide
My presentation about XYZ
---
Second slide
Hello world
</textarea>
<script src="https://remarkjs.com/downloads/remark-latest.min.js"></script><script>remark.create();</script>
</html>
which options are there, using HTML or Javascript or Markdown-specific syntax to have both languages in the same file like this:
<textarea id="source">
First slide ||| Première diapositive
My presentation about XYZ ||| Ma présentation à propos de XYZ
---
Second slide ||| Seconde diapositive
Hello ! ||| Bonjour
</textarea>
<javascript>
chooseLanguage(document.getElementBydId('source'), 'en'); // there is surely a better solution
// than a parsing and splitting by '|||' ?
</javascript>
As a way to better organize localized texts, you could use CSS classes to mark which language applies to each text.
Remark provides a markdown extension called "Content classes" (https://remarkjs.com/#12), it's used to apply CSS classes to texts.
I think this feature could be exploited to wrap localized texts inside the markdown source, in this fashion:
.lang_en[Second slide]
.lang_fr[Seconde diapositive]
.lang_it[Seconda diapositiva]
These will be transcripted in HTML as:
<span class="lang_en">Second slide</span>
<span class="lang_fr">Seconde diapositive</span>
<span class="lang_it">Seconda diapositiva</span>
Once texts are structured this way, you can easily show / hide them via javascript and CSS.
This fiddle shows the Remark boilerplate localized in english and italian, adapted using the above strategy (javascript language switcher not provided in the snippet): https://jsfiddle.net/k7au5oe3/

Pig Latin translator using a While Loop in Javascipt

My son is teaching himself JavaScript. (He’s too young to have an account here.) He’s trying to write a Pig Latin translator using a “while loop.” The basic question he right now is how to sequence the code - so the user types in the word, then the program translates it, then the result appears in the alert box. He’s brand new to this, so if anyone has any friendly feedback it would be much appreciated.
Here’s what he’s got:
<HTML>
<HEAD>
<SCRIPT LANGUAGE="Javascript">
<!-- Beginning of JavaScript -
</SCRIPT>
</HEAD>
<BODY bgcolor="Blue">
<h3> Type some text then click TRANSLATE. </h3>
<FORM>
<INPUT NAME="wordToTranslate" TYPE=Text>
<INPUT NAME="submit" TYPE=Button VALUE="TRANSLATE" onClick="alert(form.wordToTranslate.value)" style="font-size:1em;background:lime">
</FORM>
<script>
while (wordToTranslate.substring(0, 1) = bcdfghjklmnpqrstvwxyz) {
console.log(var wordWithoutFirstLetter = wordToTranslate.slice(0, 1);
var wordWithoutLastLetters = wordToTranslate.slice(1) var wordToTranslate = wordWithoutFirstLetter + wordWithoutLastLetters;
++
wordToTranslate + ay
</script>
Oh my, there are a lot of errors in this code. I would really recommend trying some easier examples first. But to save you some time in the future, here are (some) of the issues I see in your JavaScript. Every one of these will cause an error and stop the code from running.
The primitive strings are not inside quotation marks or apostrophes (for instance, bcdfghjklmnpqrstvwxyz should be "bcdfghjklmnpqrstvwxyz")
Attempting to log syntax rather than a string (or object that can be converted to a string): console.log(var ...) will cause an error
Using an increment (++) operator on a string variable...
some parentheses are missing closing parentheses, and the curly bracket has not closing curly bracket
you never actually get the string to use from the HTML element (i.e., the "value" of the <INPUT>).
After working with some easier examples first and building up to this, I would suggest googling a JavaScript pig latin example and using it as a reference to learn the more complicated concepts (like matching the first letter to a consonant). Good luck!
Since you're looking for general help, I would gently suggest that if he's learning JavaScript and HTML that he learn the newer versions, namely HTML5 , ES6+, and CSS3.
Below is essentially what he has so far--Pig Latin translation code not included--but moved to the newer standards.
'use strict';
const btnTrans = document.getElementById('btnTrans');
const txtWord = document.getElementById('txtWord');
btnTrans.addEventListener('click', translate);
function translate() {
console.log(txtWord.value);
}
body {
background-color: blue;
}
button {
font-size: 1em;
background:lime
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form>
<input name="wordToTranslate" id="txtWord" type="text">
<button type="button" id="btnTrans">Translate</button>
</form>
</body>
<script src="script.js"></script>
</html>
Note the DOCTYPE on the html. Also, all of the HTML elements are lowercase and the attribute values are quoted. JavaScript side, the event listener for the button click event is wired up in the JavaScript code, not in the HTML. The variables are set using const, which is scoped differently than var. I've also moved the inline styles to a CSS file and gotten rid of the old, deprecated ones like bgcolor.
Separating the code into separate files like this creates a clear responsibility for each part of the overall app: the HTML is the view; the CSS styles that view and can be overridden or changed in the future; the JavaScript acts as the controller.
I don't really expect this to be selected as the answer to this question; rather, it's general advice for a general question and new-to-the-web-world programmer. Welcome aboard! =)

How to preserve c++ template code in html? [duplicate]

This question already has answers here:
How to display raw HTML code on an HTML page
(30 answers)
Closed 8 years ago.
I'm writing a C++ Style Guide for my company in html/css/javascript. I'm quite irritated with html as it treats anything between < and > as html tag and thus processes them as well. As a result of which my code (which I put in the style guide) doesn't look as such. Here is an example:
<pre>
std::vector<std::string> get_project_names();
template<typename Printable>
void print(Printable const & item);
template<typename FwdIterable, typename Predicate>
FwdIterable find_if(FwdIterable begin, FwdIterable end, Predicate pred);
</pre>
and I want the browser to render it exactly like that, but it doesn't render so, e.g Chrome doesn't show <std::string> part, and IE 8.0 capitalize <std::string> as <STD::STRING> (and all such template codes).
I don't want any kind of interference by html engine. Is there any simple way to achieve what I want? Any polite way to tell the browser to not modify my code?
Note that replacing < with < and > with > would work, but it is cumbersome to write it everytime I write a template code. It also makes my code difficult to read in the source code of the html. So I'm looking for a simple solution.
The notion of a "polite way to to tell the browser to not modify (parse) my code" is precisely what XML's CDATA does. Nothing more, nothing less.
CDATA does not exist in HTML, so there is no way in HTML to treat <std:vector> as anything other than on opening tag for the (non-existent) std:vector element.
The normal way to do this is a server-side transformation. Now if you aren't generating your HTML server-side, and are instead writing it by hand, you can make your life just a dash easier with a client-side transformation like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Page Title</title>
<script src="http://coffeescript.org/extras/coffee-script.js"></script>
</head>
<body>
<pre><script type="text/coffeescript" >document.write "
std::vector<std::string> get_project_names();
".replace('<','<')
</script></pre>
</body>
</html>
Here I used CoffeeScript because of its multiline string capability which is coming in ES6 for regular JavaScript. It makes it easy to just drop in your code between the boilerplate lines.
Now I know full well even this solution is lacking! If your inserted code contains a " you're out of luck. And it doesn't escape ampersands.
Bottom line is that there is no CDATA, so no "simple" solution exists. A transformation, client-side or server-side, is required.
Have you tried markdown?
I've been dealing with this particular problem for years, and it's always been frustrating. I've always appreciated the simplicity and elegance of Markdown, so I did a little research to see if there was any way to use Markdown to build an HTML document.
Thing is, code samples sometimes involve HTML, yet HTML is the language we're using to write style guides and API documentation, so my thought was that if we wrote the API documentation and style guides in Markdown, we'd eliminate all of the conflicts between HTML and the syntax of other languages.
I found Strapdown.js, which is a library that allows you to create a Web page with pure Markdown. The library then compiles it to HTML and renders it on the page client side. We put together the API documentation for one of our products using this library, and we published it as a GitHub page.
Here's a small, concise example:
<!DOCTYPE html>
<html>
<title>JavaScript API</title>
<xmp theme="united" style="display:none;">
## Print the name
Print the user's name:
```javascript
function printName(name) {
alert(name);
}
```
</xmp>
<script src="http://strapdownjs.com/v/0.2/strapdown.js"></script>
</html>
Everything inside the <xmp> tags gets compiled to HTML.
Note: The XMP tag has been deprecated for some time as per the Mozilla HTML documentation on XMP. Thus, you may want to either hack the code to make it use PRE or CODE, or you may want to consider using the lower-level Marked library that was used to build Strapdown.js. I filed an issue with the Strapdown.js team.
For that you can use this
<pre>
std::vector<std::string> get_project_names();
template<typename Printable>
void print(Printable const & item);
template<typename FwdIterable, typename Predicate>
FwdIterable find_if(FwdIterable begin, FwdIterable end, Predicate pred);
</pre>
This would be encoded and you'll get the result that you want.
Here is the fiddle for that: http://jsfiddle.net/afzaal_ahmad_zeeshan/7B9xB/
JavaScript code
The JavaScript method of doing this would be simple, you can convert the whole code to a String variable.
As this
var string = "content here";
Then apply this,
string.replace('<','<').replace('>','>');
Convert all the characters and then have then rendered by the Browser.
http://jsfiddle.net/afzaal_ahmad_zeeshan/7B9xB/1/
For my book I used http://markup.su/highlighter/ syntax highlighter. Paste the code into it, generate highlighted code, and paste the latter into the HTML document. Worked pretty well. Here's a fiddle with your code: http://jsfiddle.net/6GTs2/.
Here's your code highlighted for HTML:
<pre style="background:#000;color:#f8f8f8">std::vector<std::string> <span style="color:#89bdff">get_project_names</span>();
<span style="color:#99cf50">template</span><<span style="color:#99cf50">typename</span> Printable>
<span style="color:#99cf50">void</span> <span style="color:#89bdff">print</span>(Printable const & item);
<span style="color:#99cf50">template</span><<span style="color:#99cf50">typename</span> FwdIterable, <span style="color:#99cf50">typename</span> Predicate>
FwdIterable <span style="color:#89bdff">find_if</span>(FwdIterable begin, FwdIterable end, Predicate pred);
</pre>

javascript heading as variable not using PHP

The problem is simple: I want to show a different heading depending on an internal variable in javascript, using NVD3. I've tried different things, learnt how <title> works and used it, but I could not get to the point. This is a very simplified version of the code:
<body>
<h1> [Here I want show some the content of the variable myheading] </h1>
</body>
myheading= "This is the head of a specific plot";
I hope the answer is not too obvious, I've been looking for it for a while...
This should do it:
<h1 id="target">PlaceholderText</h1>
document.getElementById("target").innerHTML = myheading;

Is using custom HTML tags and replacing custom tags with outerHTML okay?

Is it alright to define and use custom tags? (that will not conflict with future html tags) - while replacing/rendering those by changing outerHTML??
I created a demo below and it seems to work fine
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<script type="text/javascript" src="jquery.min.js"></script>
</head>
<body>
<div id="customtags">
<c-TextField name="Username" ></c-TextField> <br/>
<c-NameField name="name" id="c-NameField"></c-NameField> <br/>
<c-TextArea name="description" ></c-TextArea> <br/>
<blahblah c-t="d"></blahblah>
</div>
</body>
<script>
/* Code below to replace the cspa's with the actual html -- woaah it works well */
function ReplaceCustomTags() {
// cspa is a random term-- doesn;t mean anything really
var grs = $("*");
$.each(grs, function(index, value) {
var tg = value.tagName.toLowerCase();
if(tg.indexOf("c-")==0) {
console.log(index);
console.log(value);
var obj = $(value);
var newhtml;
if(tg=="c-textfield") {
newhtml= '<input type="text" value="'+obj.attr('name')+'"></input>';
} else if(tg=="c-namefield") {
newhtml= '<input type="text" value="FirstName"></input><input type="text" value="LastName"></input>';
} else if(tg=="c-textarea") {
newhtml= '<textarea cols="20" rows="3">Some description from model</textarea>';
}
obj.context.outerHTML = newhtml;
}
z = obj;
});
}
if(typeof(console)=='undefined' || console==null) { console={}; console.log=function(){}}
$(document).ready(ReplaceCustomTags);
</script>
</html>
Update to the question:
Let me explain a bit further on this. Please assume that JavaScript is enabled on the browser - i.e application is not supposed to run without javascript.
I have seen libraries that use custom attributes to define custom behavior in specified tags. For example Angular.js heavily uses custom attributes. (It also has examples on custom-tags). Although my question is not from a technical strategy perspective - I fail to understand why it would strategically cause problems in scalability/maintainability of the code.
Per me code like <ns:contact .....> is more readable than something like <div custom_type="contact" ....> . The only difference is that custom tags are ignored and not rendered, while the div type gets rendered by the browser
Angular.js does show a custom-tag example (pane/tab). In my example above I am using outerHTML to replace these custom tags - whilst I donot see such code in the libraries - Am I doing something shortsighted and wrong by using outerHTML to replace custom-tags?
I can't think of a reason why you'd want to do this.
What would you think if you had to work on a project written by someone else who ignored all common practices and conventions? What would happen if they were no longer at the company to find out why they did something a certain way?
The fact that you have to just go through with JavaScript to make it work at all should be a giant red flag. Unless you have a VERY good reason to, do yourself a favor and use the preexisting tags. Six months from now, are you going to remember why you did things that way?
It may well work, but it's probably not a good idea. Screen readers and search engines may have a hard/impossible time reading your page, since they may not interpret the JavaScript. While I can see the point, it's probably better to use this template to develop with, then "bake" it to HTML before putting it on the server.

Categories