JavaScript Beginner Level - Need help understanding Math.random and "quotes.length" - javascript

and I need help understanding some parts of this
Example I am doing out the Sams Teach Yourself HTML, CSS, and JavaScript.
A few things they did not explain in the lesson is this line here
"i = Math.floor(Math.random() * quotes.length);"
How does quotes.length and Math.random work?
Also I am having a hard time understanding this block of code..
"//Write out the quote as HTML
document.write("<p style='background-color: #ffb6c1'>\"");
document.write(quotes[i] + "\"");
document.write("<em>-" + sources[i] + "</em>");
document.write("</p>");"
Any help will be appreciated.
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Quotable Quotes</title>
<script>
<!-- Hide the script from old browsers
function getQuote() {
//Create the Arrays
var quotes = new Array(4);
var sources = new Array(4);
// Initialize the arrays with quotes
quotes[0] = "When I was a boy of 14, my father was so " +
"ignorant...but when I got to be 21 I was astonished" +
"at how much he had learned in 7 years.";
sources[0] = "Mark Twain";
quotes[1] = "Everybody is ignorant. Only on different " +
"subjects.";
sources [1] = "Will Rogers";
quotes[2] = "They say such nice things about people at " +
"their funerals that it makes me sad that I'm going to " +
"miss mine by just a few days.";
sources[2] = "Garrison Keillor";
quotes[3] = "What's another word for thesaurus?";
sources[3] = "Steven Wright";
//Get a random index into the arrays
i = Math.floor(Math.random() * quotes.length);
//Write out the quote as HTML
document.write("<p style='background-color: #ffb6c1'>\"");
document.write(quotes[i] + "\"");
document.write("<em>-" + sources[i] + "</em>");
document.write("</p>");
}
// Stop hiding the script -->
</script>
<meta name="viewport"
content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Quotable Quotes</h1>
<p>Followinhg is a randon quotable quote. To see a new quote just reload this page</p>
<script>
<!-- Hide the script from old browsers
getQuote();
// Stop hiding the script -->
</script>
</body>
</html>

Math.random() produces a random number between 0 and 1. And quotes.length wll return the number of items in the quotes array, which in your case is 4.
In the code, you are trying to get a random quote from the quotes array. And you must be knowing by now that to access an element from an array we have to use index.
So by this line, we are generating a valid random index that could help us get a quote out from the quotes array.
If you think, maximum length of quotes array could be 4 multiplied by (take the biggest random number Math.random() could generate) 0.9 which would be less than 4 and a float, so Math.floor takes care of that and rounds the number downwards to the nearest integer making it equal to 3 which is the last quote. And in this way you get random quotes.
i = Math.floor(Math.random() * quotes.length);
Now onto this:
It's just writing html to the DOM (Document Object Model). DOM defines the logical structure of the documents and the way in which they are accessed and manipulated.
So basically you are just writing the html encapsulated in the quotes to the document.
document.write("<p style='background-color: #ffb6c1'>\");
document.write(quotes[i] + "\"");
document.write("<em>-" + sources[i] + "</em>");
document.write("</p>");"

Related

I need some troubleshooting with my HTML/JavaScript code

I am trying to create code that when you press a button, it will change the value of a variable and replace some text.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<p id="unitts">You have 0 unitts</p>
<script type="text/javascript">
var unitt = 0;
function unittIncrease() {
var unittPrev = unitt;
unitt++;
document.getElementById(unitts).innerHTML.replace("You have " + unittPrev.toString() + " unitts.", "You have " + unitt.toString() + " unitts.");
}
</script>
<button id="unittIncrease" onclick="unittIncrease();">Digitize Unitt</button>
</body>
</html>
When I press the button, nothing happens to the text.
I don't know why this does not work.
Please help me!
EDIT: I am only 11 years old,
please don't throw your wizard
code at me.
maybe you should remove your button system and add a while loop that
automatically add a unit but waits one second with a setInterval
function
I think you should write the js code like this
document.getElementById('unitts').innerHTML = "You have"....
Instead of:
document.getElementById(unitts).innerHTML.replace("...")
Your JavaScript should be (note the unitts wrapped in quotes and the full stop removed):
document.getElementById('unitts').innerHTML = "You have " + unitt + " unitts";
Instead of:
document.getElementById(unitts).innerHTML.replace("You have " + unittPrev.toString() + " unitts.", "You have " + unitt.toString() + " unitts.");
In the latter, it is looking for the non-existent variable unitts instead of the string 'unitts'. Also, you are looking for the text You have x unitts. which cannot be found because in your HTML, it is just You have x unitts without the full stop.
Edit
See this plnkr.
Apart from the issues that the other answer mentions, by calling .replace method on the .innerHTML property of the element, the content of it doesn't change. You should reset the property by using the returned value of the method call:
el.innerHTML = el.innerHTML.replace(...);
Also, as you are trying to increase a number, instead of replacing all the characters, you can just replace the numeric part:
var unitts = document.getElementById('unitts');
function unittIncrease() {
unitts.textContent = unitts.textContent.replace(/\d+/, function(n) {
return +n + 1;
});
}
https://jsfiddle.net/h6odbosg/

Using Javascript and for loop function to render 2 times multiplication string

So this is what I have so far, I know I'm on the right track but I can't figure out to create a var for totting up the results and integrating that into my code...I understand that the var created for the multiplication should go after the last "+" in my "for" line.
<!DOCTYPE html>
<html>
<body>
<p></p>
<button onclick="loop()">Click here</button>
<p id="forLoop"></p>
<script>
function loop() {
var total = "";
var x;
for (x = 1; x < 13; x++) total += "2 x " + x + " = " + "<br>";
document.getElementById("forLoop").innerHTML = total;
}
</script>
</body>
</html>
You don't need another var. You can just use x*2. JavaScript is smart enough to evaluate the result and add it to the string as you would expect.
"2 × " + x + " = " + x*2 + "<br />"
Few notes:
To denote "times" (like: "a times b"), HTML has the × entity which renders like so: ×
It's considered bad practice to use <br> like this in production. Generate a table or a list, and add those as elements.
You should avoid .innerHTML until you are aware of the risks of using it.

HTML in JavaScript function basics

Ok, I'm having a huge problem, and I've been looking for days about how to do this. Either I can't read well enough to understand it, or I'm stupid. I'm not sure what it is yet. I'll be honest and say that this is homework, but I've been struggling with this for 3 days now, and as its an online class, I can't go see my instructor and ask him what I'm doing wrong. I have emailed him, but his help is limited and vague, and I cannot figure this out. Anyway, to the point. I want to add HTML to the text that's going to be displayed in a new window using a JavaScript function. Here's the basics of what I have.
function myWindow(){
var pageContent, pageTitle;
pageTitle = document.write("Selected Image Preview");
document.write.style.textAlign="center";
pageContent = "<html><head><title>";
pageContent += pageTitle + "</title>";
pageContent += "<script>alert('The page ' + document.title + ' was created: ' + document.lastModified)</script>";
pageContent += "<h3>"Name of Image"</h3>";
pageContent += "</head><body align="center"><strong>" + "<font color= " violet ">"Here is the image you selected. "</font>";
pageContent += "</strong></body></html>";
}
Now, I have no idea what I'm doing wrong, considering I've read almost everything that I could find, searched all over this site, as well as dozens of others. I've tried the W3 schools, and some site that looked like it was last updated in 2001, and my book has absolutely NO examples of HTML being used inside the function (it's a javascript book, so the HTML help is very limited). Starting at the top, it tells me that "Uncaught SyntaxError: Unexpected token ILLEGAL junk.html:16" on the script line. Then it won't load the rest of the page. If I comment that out, it tells me that '<h3>' is an unexpected identifier, and it just keeps going. There's always something wrong and if I comment out the lines that give errors, then there's nothing left. Please help me figure out what I'm doing wrong. And if it's necessary, I am calling the function onload with the <body onload="myWindow();"> tag.
P.S. Please don't kill me if I've formatted this incorrectly. I did read the directions, and tried to format this as neatly as possible.
The biggest problem was that the closing </script> tag in the line with the call to alert() terminated the script, even though it was within a string literal. See the link in my comment to your original post. There were some other problems with quotes, and if a teacher is really teaching the <font> tag in 2014, I think I should track him down and throw up in his lap.
Note that the slash in </script> and the embedded double-quotes are now escaped with backslashes. That's the biggest change. Also, the function now returns the computed value so it can be used.
This code goes through a JavaScript console clean. It doesn't open any new windows, and it doesn't deal with the "style" line, which I couldn't figure out.
function myWindow(){
var pageContent, pageTitle;
pageTitle = "Selected Image Preview";
// document.write.style.textAlign="center"; // WTF?
pageContent = "<html><head><title>";
pageContent += pageTitle + "</title>";
pageContent += "<script>alert('The page ' + document.title + ' was created: ' + document.lastModified)<\/script>";
pageContent += "</head>";
pageContent += "<body style=\"text-align: center;\">";
pageContent += "<h3>Name of Image</h3>";
pageContent += "<strong>" + "<font color= \" violet \">\"Here is the image you selected. \"</font>";
pageContent += "</strong></body></html>";
return(pageContent);
}
I've edited the code. The <h3> line was within the head of the document, now fixed, and I added a style attribute to <body> based on your remark about wanting text centered.
Ok, your code contains errors, because you need to learn how to work with strings and quotes and how to escape quotes.
var str1 = "qwe";
var str2 = "asd";
var str3 = str1 + str2; // will be qweasd
var str3 = str1 + '1111' + str2; // will be qwe1111asd
var str3 = str1 + 'z"1"' + str2; // will be qwez"1"asd
var str3 = str1 + "z\"1\"" + str2; // will be qwez"1"asd. There is no difference if you use double quotes or single. If you use single quotes, all single quotes in the string must be escaped with backslash and opposite with double quotes
// and the same with single quotes:
var str3 = str1 + 'z\'1\'' + str2; // will be qwez'1'asd
also, you are using document.write function, which overrides the content of current page, but you need a new window, which is why we should use function window.open which returns a new window handler. We save it into OpenWindow variable and then we apply our content using OpenWindow.document.write passing our string pageContent as a first parameter
and the correct code:
function myWindow(){
var pageContent, pageTitle;
document.title = "Selected Image Preview";
document.body.style.textAlign="center";
pageContent = "<html><head><title>";
pageContent += pageTitle + "</title>";
pageContent += "<script>alert('The page ' + document.title + ' was created: ' + document.lastModified)</script>";
pageContent += "<h3>Name of Image</h3>";
pageContent += '</head><body align="center"><strong><font color="violet">Here is the image you selected.</font>';
pageContent += "</strong></body></html>";
var OpenWindow = window.open('#','_blank','width=335,height=330,resizable=1');
OpenWindow.document.write(pageContent);
}
pageContent += "<h3>"Name of Image"</h3>";
You don't need quotes around name of image. The entire line should be treated as a String.
pageContent += "<h3>Name of Image</h3>";
Basically, anything in HTML tags doesn't need quotes unless you intend for quotes to appear.
For this line:
pageContent += "</head><body align="center"><strong>" + "<font color= " violet ">"Here is the image you selected. "</font>";
You should use single quotes.
pageContent += "</head><body align='center'><strong>" + "<font color='violet'>Here is the image you selected. </font>";
You should be able to fix the rest of your HTML, keeping in mind single quotes for attributer, no quotes for content.
As to the HTML itself, it should look like this to follow at least intended standards. You should move most of the styles eventually to CSS.
<html>
<head>
<title>Selected Image Preview</title>
<script>// your script here </script>
</head>
<body>
<div align='center'>
<!-- your content here -->
</div>
</body>

Trouble getting a Javascript function to run

I am still fairly new to Javascript and I am having some trouble getting a function to run properly. Here is what I have:
<script type='text/javascript'>
function GravityCalc (ratio, name)
{
Weight = getElementById('WeightBox').value * ratio;
document.getElementById('WeightText').innerHTML = 'You would weigh ' + weight + ' on ' + name;
}
</script>
Enter Weight: <input type='text' id='WeightBox' name='Weight'><br>
<button onclick='GravityCalc(2.3,Jupiter)'>calculate</button>
<div id='WeightText'> </div>
The form displays perfectly, but nothing happens when the button is pressed. It also should probably be noted that eventually, the name and ratio parameters is going to be parsed in with PHP.
You have a couple things wrong...
'Weight' should be 'weight'. JS is case sensitive, and you had it in Camel case in one line and Pascal case in another line.
You need to use 'document.getElementById'. Just 'getElementById' doesn't work in all browsers.
You need to declare the 'Weight' variable.
The value in a dom element is stored as a string or char array if you will, thus you need to parse it to an int, like so, parseInt(document.getElementById('WeightBox').value)
Here's my JSFiddle... http://jsfiddle.net/EH5j6/
function GravityCalc (ratio, name)
{
var weight;
weight = parseInt(document.getElementById('WeightBox').value) * ratio;
document.getElementById('WeightText').innerHTML = 'You would weigh ' + weight + ' on ' + name;
}
javascript variables are case sensitive! Your Ws didn't match up. I also highly recommend using var to explicitly declare your variables.
var weight = getElementById('WeightBox').value * ratio;
document.getElementById('WeightText').innerHTML = 'You would weigh ' + weight + ' on ' + name;
plus, as a commenter noted, strings must be enclosed by quotes.
<button onclick='GravityCalc(2.3,"Jupiter")'>calculate</button>
Make sure that you include the javascript in the head of the html page.
function calc (ratio, name) {
var weight = document.getElementById('WeightBox').value * ratio;
document.getElementById('WeightText').innerHTML = "You would weigh " + weight + " on " + name;
}
and change the HTML to be:
Enter Weight: <input type='text' id='WeightBox' name='Weight'><br>
<button onclick="calc(2.3, 'Jupiter')">calculate</button>
<div id='WeightText'> </div>

Can someone tell me if they see this

I am having problems when I try to pull it up on my computer the page is blank. I am not understanding this. Like when you click on the file button on the internet and you click open file that file shows up blank. Can someone help me understand why it is doing that. Thanks.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Week 10</title>
<script type="text/javascript">
/ *<![CDATA[ */
Var name;
firstName = "Valerie";
lastName ="Shipbaugh";
var placeOfBirth;
name=FirstName +"";
name += lastName;
placeOfBirth ="Houston";
placeOfBirth +=",Texas";
nameArray = name.split("");
/*]]>*/
</script>
</head>
<body>
<script type="text/javascript">
//<![CDATA[
document.write("<p> My first name is : + nameArray[0]
+ "<br />");
document.write("My last name is: "+ nameArray[1]
+ "<br />");
*/
The brackets[] specifies alternate characters allowed in a patch pattern.
It uses metacharacters which are special characters that define the pattern matching rules ina regular experession.
*/
document.write("There are " + firstName.length
+ " characters in my first name" + " <br/>");
*/
This one called the length property.
This returns the number of characters in a string.
*/
document.write("I was born in " + placeOfBirth + " <br/>");
*/
With this string we are using concatenation operations.
*/
document.write("<p>My initials are: " + firstName.charAt(0) +
lastName.charAt(0) + "</p>");
*/
The last one return the character at the specific position in a text string
returns an empty string if the specified position is greater than the length of the string.
*/
//]]>
</script>
</body>
</html>
So where my comments are to explain what is going on is in the wrong place???
There is a more general way to solve this problem:
Take everything out of this file and
copy it into notepad.
Put just the
<html>and </html> into the file
Begin copying very small blocks into
the file one at a time, each time
reload the page
Soon you will see
one small block that causes the
failure, then you can assess that
small block.
Look at errors reported by the browser (tools->error console in firefox for example) it will hi-light errors such as you mismatched /**/ comments & the missing closing quote character from;
document.write("<p> My first name is : + nameArray[0]
Also js is case sensitive so its var not Var, which you should use to define all your variables such as firstname (which you incidentally later refer to as Firstname) etc.
Of course it won't work, the comment blocks aren't even right:
*/
The brackets[] specifies alternate characters allowed in a patch pattern.
It uses metacharacters which are special characters that define the pattern
matching rules ina regular experession.
*/
Should be:
/*
The brackets[] specifies alternate characters allowed in a patch pattern.
It uses metacharacters which are special characters that define the pattern
matching rules ina regular experession.
*/
Also, you really should avoid using document.write. In certain cases, that is what causes a blank page (if I remember correctly, when you use it after page load).
JavaScript is case sensitive - so in the first section of your scripts:
Var name; //var is with a lowecase "v"
firstName = "Valerie";
lastName ="Shipbaugh";
var placeOfBirth;
name=FirstName +""; //firstName was created with a lowecase "f"
Later you have this...
document.write("<p> My first name is : + nameArray[0]
+ "<br />");
You're missing a quote in there, should be
document.write(" My first name is : " + nameArray[0]
+ "");
And finally, comments open and close like this:
/* comment */
Not like this
*/ error */
Fixing these things will make the script run. However, it's not doing what I suspect you want. You are trying to split() the string containing the name, but there's nothing to split it on. You need to add a space between then and try this:
nameArray = name.split(" ");
You can see this working here:
http://jsfiddle.net/CM7fx/
Test in multiple browsers and make sure you have javascript enabled id' suggest first
The comments were wrong, the variable name are case sensitive. Here is a working version without comments, you can re-add those
<head>
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<title>Week 10</title>
<script type="text/javascript">
var name;
var firstName = "Valerie";
var lastName ="Shipbaugh";
var placeOfBirth;
name= firstName + " " + lastName;
placeOfBirth ="Houston ,Texas";
var nameArray = name.split(" ");
</script>
</head>
<body>
<script type="text/javascript">
document.write("<p> My first name is : " + nameArray[0] + "<br />");
document.write("My last name is: " + nameArray[1] + "<br />");
document.write("There are " + firstName.length + " characters in my first name" + " <br/>");
document.write("I was born in " + placeOfBirth + " <br/>");
document.write("<p> My initials are: " + firstName.charAt(0) + lastName.charAt(0) + "</p>");
</script>
</body>
</html>

Categories