Pig Latin translator using a While Loop in Javascipt - javascript

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! =)

Related

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.

HTML input into Javascript

I want to create a website which can tell the circumference of a circle when the user inputs the radius. I've done the code, but its not working. Can you tell me why?
<html>
<head>
</head>
<body>
<form id="ty">
Give radius: <input type="number" input id="radius">
</form>
<p id="sum"> htht </p>
<button type="button" onclick="my()"> Click on me</button>
<script>
Function my() {
var r= document.getElementById("radius");
var a= r*2;
document.getElementById("sum").innerHTML=a;
}
</script>
</body>
</html>
I am getting an error "NaN" when I click on the button
Working HTML demo:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Language" content="en">
<meta charset="UTF-8">
<title>Radius to Circumference</title>
</head>
<body>
<form name="ty">
<ol>
<li>Give radius: <input type="number" name="radius"></input></li>
<li><input type="button" onClick="my();" value="convert"></input></li>
<li>Get circumference: <input type="number" name="sum"></input></li>
</ol>
</form>
<script LANGUAGE="Javascript">
function my() {
var r = document.ty.radius.value*1;
var a = r*2;
document.ty.sum.value = a;
}
</script>
</body>
</html>
when writing HTML, you should be certain to use proper semantics.
Specify a doctype, character set and language!
avoid using buttons that say things like "Click on me!" This is
redundant because the user has to read what they're going to do
before they do it. Instead, write what the button will do
on the button itself (in this case, "Convert" is what I used).
you did not include a title in your head.
and are two different elements with different
purposes. In this case, you want .
"function" should not be capitalized.
your r variable did not contain the number the user put in, but
rather, contained all the properties of the input element. You never
specified you wanted the number it contained, so instead, the
variable r contained all the information it could obtain about the
"radius" element including it's colour, it's size, and other useless
things you don't need. You are looking for it's value, hence why I
added .value on the end of that line.
I also added *1 to the end of r's line, so that if the user by
any chance did not enter a valid number, Javascript will correct that
issue (multiplying by one gives the same result but parsed into a number).
you were using the p element for the sum, but that wouldn't be a
paragraph now, would it?
I used an ordered list to add 1, 2, and 3 to the beginning of each
step.
I think you mean:
var r = document.getElementById("radius").value;
getElementByID returns the element, not its value. element*2 = NaN.
You want.
var r = document.getElementById("radius").value;
Also, you might want to parse the integer just in case:
var r = parseInt(document.getElementById("radius").value);
Very simple, from HERE you can find you need to change:
var r= document.getElementById("radius");
to
var r= document.getElementById("radius").value;
You have written whith uppercase F the function, note that the
javascript is case sensitive.
the value of the input element can get using the .value property.
in the input form element does not need twice using the input
keyword, only once on begin.
Here is a nicer way to write that, with some minor improvements.
it's preferred to write the javascript in the head.
by defining the various elements onload later you have faster&easier access to them.
also inline javascript is not suggested, don't write js inside html attributes.
Then talking about your errors:
function is not Function
document.getElementById('radius') should be document.getElementById('radius').value
<html>
<head>
<script>
var radiusBox,sumBox,button;
function my(){
sumBox.innerHTML=radiusBox.value*2
// the use of textContent is more appropiate but works only on newer browsers
}
window.onload=function(){
radiusBox=document.getElementById('radius');
sumBox=document.getElementById('sum');
button=document.getElementById('button');
button.onclick=my
}
</script>
</head>
<body>
<form id="ty">
Give radius:<input type="number" id="radius">
</form>
<p id="sum">Enter a number</p>
<button id="button">Click on me</button>
</body>
</html>
writing it this way it is compatible with every browser that supports javascript, a newer proper way would be using addEventListener to add the load and the click handler thus also allowing you to add multiple event handlers, but old ie's wouldn'ty work.also textContent could have prblems...
DEMO
http://jsfiddle.net/frma0zup/
if you have any questions just ask.

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>

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.

use eval to evaluate a javascript snippet in a textarea?

I'm at my first hackathon and trying to finish my project. I am very very new the javascript... everything I know I literally learned in the last 2 hours. That being said...
So I know that eval is not the greatest thing to use, but I'm trying to write a simple program in which you can input a javascript snippet into a textarea, click an execute button, and have the javascript execute inside another textarea. I'm trying to stay away from jquery for now, because I want to get the really basic idea down before I add another level of complexity, which is why I'm not using id's.... but if jquery is the only way to do this, then I guess I'll have to pony up and learn it in the next 8 hours.
Code as follows (ish):
function executeJS ()
{
var result = eval(game.input.value);
game.execute.value=result;
}
<head>
<body>
<H1>PRogram</H1>
<form name="game">
<textarea name="execute" rows="5" cols="30" value=""></textarea><br>
<textarea type="text" name="input" rows="10" cols="30" value=""></textarea>
<input type = "button" value = "guess" onclick = "executeJS()</input>
</form>
</body>
</head>
I'm not getting an output in my execute box.
Any insight would be much appreciated.
"game" isn't a variable. it's a DOM element name.
if you want to get it's object, give it an id let's say "game", and use document.getElementById('game')
Note that your <head> surround the <body>
Your javascript code isn't inside <script></script tag.
Here is a working version. However, I would reconsider your idea of not using IDs or libraries:
function executeJS() {
var game = document.forms['game'];
var result = eval(game.input.value);
game.execute.value = result;
}
And be wary of eval.

Categories