Arithmetic sequence within an array using doc.write to display Javascript - javascript

So the objective is to make an arithmetic sequence starting 7 with difference of 9. So 7, 16, 25, 34 etc.
You have to do this 20 times and make a one column table that autogenerates the rows per number using document.write() to print it.
I believe I understand to make an array of 20 and input the math within the array. So this is what I have so far,
<!DOCTYPE html>
<html lang="en">
<head>
<title>Javascript Arithmetic Sequence</title>
<meta charset="UTF-8" />
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
</head>
<body>
<script type ="text/javascript">
var result =[20];
for (var a = 7; a + 9; a++) {
document.write("<table>"+
"<tr>"+
"<th> Arithmetic Sequence of 7</th>"+
"<td>"+ result+"</td>"+
"</tr>"+
"</table>");
}
</script>
<p>Question 1: You would need to change the array length.</p>
<br>
<p>Question 2: You use document.write() to display HTML document content and not pop up as a button/alert using alert().</p>
</body>
</html>
The problem is, nothing shows on my HTML website and the JS validators keep saying document.write() can be used as an "eval" (which I don't understand what that means). I've scanned my chapter up and down, googled some advice (which goes way outside what the chapter is about). Looking to see if anyone can spot where I might be wrong or give advice on what I need to adjust.
Thanks.

Played around with it and finally got the answer. Thanks everyone who helped too!
<script type ="text/javascript">
var table = "<table border =1><tr><th>Arithmetic Sequence of d=9</th></tr>";
var result = 7 ;
for (var count = 0; count <20; count++) {
result = result + 9;
table+="<tr><td>"+ result +"</td>",
"</tr>";
}
table+="</table>";
document.write(table);
</script>

Related

Javascript in HTML, struggling to make a for loop work for a button

I'm trying to practice using JavaScript in HTML, and am having some trouble.
The goal for me right now is to have a button that, when pressed, prints out a series of breaks and descending numbers down to 1 like a countdown. Once I've got the function implemented into the page, I'd work in a textbox that the user can use to have their own number that counts down to 1. Pretty simple, but I've hit a wall. I'm trying to do this using a .js library located in the same folder as the HTML file. Here's how my HTML looks:
<!doctype html>
<!-- project10.html -->
<html>
<head>
Hello!
</head>
<body>
<title>Testing Function</title>
<script type="text/javascript" src="test.js"></script>
<p id="demo" onclick="myFunction(5)">Click this text to show a countdown.</p>
</body>
</html>
Not the cleanest, I know. Here's the test.js located in the same folder:
function myFunction(b2){
for (i=b2;i>0;i--){
document.getElementById("demo").innerHTML = i;
document.getElementById("demo").innerHTML = "<br>";
}
}
As I see the question, the task is to provide a function a number, and output it in a descending order.
I've created an ul element which will you can append an li tag too on each iteration of the loop so you can see the numbers count down.
I've also changed the p element to a button, as this is more suitable for the given task, you generally click on buttons, not paragraphs.
<html>
<head>
Hello!
</head>
<body>
<title>Testing Function</title>
<script type="text/javascript" src="test.js"></script>
<button onclick="myFunction(5)">
Click this text to show a countdown.
</button>
<ul id='list'>
</ul>
</body>
</html>
Within the Javascript file, I've used your loop, changing the name of the parameter being passed in, this was done to be as descriptive as possible.
From here, we count down, with each loop decreasing the value of the number you passed in, in your case, 5.
With each loop, we create a new li element, we then add innerHTML to it, the value of that being the current value in the loop, which is then appended to the ul element.
function myFunction(number){
const ul = document.getElementById('list')
for (i = number; i > 0; i--){
let item = document.createElement('li')
item.innerHTML = i
ul.appendChild(item)
}
}

What should I tweak in the Javascript/HTML to make this random quote generator work?

<!DOCTYPE html>
<html>
<head>
<title>Quote Gen</title>
<script src="jquery-3.1.1.min.js"></script>
<script>
var Quotes = ['Thousands of candles can be lighted from a single candle, and the life of the candle will not be shortened. Happiness never decreases by being shared.','Happiness is the art of never holding in your mind the memory of any unpleasant thing that has passed.','To be happy, we must not be too concerned with others.','Change your thoughts and you change your world.','hello'];
function newQuote(){
var RandomNumber = Math.floor(Math.random())*Quotes.length;
$("#QuoteDisplay").text(Quotes[RandomNumber]);
}
</script>
</head>
<h5>
Simple Quote Generator
</h5>
<body>
<p id = "QuoteDisplay">
</p>
<button onclick="newQuote()">New Quote!</button>
</body>
</html>
This is a simple Quote Generator that I am building as a part of FreeCodeCamp. The aim is basically to generate a new Quote whenever the user clicks on the Buttton. However when I click on the button the text isn't getting displayed. What is wrong/missing in my code?
You just need make sure that you have the JQuery library referenced BEFORE the script is encountered AND then to move a single parenthesis in this line:
var RandomNumber = Math.floor(Math.random())*Quotes.length;
So that it is:
var RandomNumber = Math.floor(Math.random()*Quotes.length);
By moving the closing parenthesis so that it comes AFTER Quotes.length, you ensure that the random number that is generated (from 0 to 1) gets multiplied by the length of the array BEFORE getting rounded down. If you don't do this, the random number will always get rounded down to 0.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Quote Gen</title>
<script src="jquery-3.1.1.min.js"></script>
<script>
var Quotes = ['Thousands of candles can be lighted from a single candle, and the life of the candle will not be shortened. Happiness never decreases by being shared.','Happiness is the art of never holding in your mind the memory of any unpleasant thing that has passed.','To be happy, we must not be too concerned with others.','Change your thoughts and you change your world.','hello'];
function newQuote(){
var RandomNumber = Math.floor(Math.random()*Quotes.length);
$("#QuoteDisplay").text(Quotes[RandomNumber]);
}
</script>
</head>
<h5>
Simple Quote Generator
</h5>
<body>
<p id = "QuoteDisplay"></p>
<button onclick="newQuote()">New Quote!</button>
</body>
</html>
Math.floor(Math.random()) always return 0 so anything you multiply it by will be 0
RandomNumber is always 0
Also, is a good practice to declare Javascript variables with the first letter lowercase.
Stick to jQuery if you're using it, avoid onclick on the DOM if you can use jQuery click event.
This is the working example with some fixes.
https://jsbin.com/meqetumini/edit?html,js,output
function newQuote(){
var RandomNumber = Math.floor(Math.random()*Quotes.length);
$("#QuoteDisplay").text(Quotes[RandomNumber]);
}
$('#new-quote-btn').click(newQuote)

Javascript not logging length correctly [duplicate]

This question already has answers here:
Is Chrome’s JavaScript console lazy about evaluating objects?
(7 answers)
Closed 7 years ago.
I'm having this issue with javascript right now where if I would console log the element itself it will show the length in chrome but it doesn't show the length correctly when I use .length.
Chrome console
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Hello World - Google Web Search API Sample</title>
<script src="https://www.google.com/jsapi"
type="text/javascript"></script>
<script language="Javascript" type="text/javascript">
google.load('search', '1');
function OnLoad() {
var searchControl = new google.search.SearchControl();
var localSearch = new google.search.LocalSearch();
searchControl.addSearcher(new google.search.WebSearch());
localSearch.setCenterPoint("New York, NY");
searchControl.draw(document.getElementById("searchcontrol"));
searchControl.execute("a");
}
google.setOnLoadCallback(OnLoad);
</script>
</head>
<body onLoad="myFunction()">
<div id="searchcontrol">Loading</div>
<script>
function myFunction() {
var y = document.getElementsByClassName('gsc-webResult gsc-result');
var y2 = y.length;
console.log(y);
console.log(y2);
}
</script>
</body>
</html>
As seen above I'm saving the element in var y and saving the length of y in y2. Then I'm console logging these variables, but it doesn't show the right length.
I'm not sure what the problem is here, I hope you can help.
Edit: Added working source code.
var y = document.getElementsByClassName('gsc-webResult gsc-result');
Returns an array of all the elements that match your query. Therefore y.length shows you the length of the array, not the length of the element.
try y[0] assuming that the element you want is first element in the array. Then length on the value assuming you want length of the text.
Also, if you only need a single element you may want to make your query more specific - but it's hard to say since you didn't post the corresponding DOM tree.

Why isn't the following javascript code working? (Crafty.js used)

I am a newbie, in crafty as well as js, so pardon me if I might have made very silly errors in the following program.
What is wrong with the following code? The following code is supposed to create 5*5 matrix where each block would be a 60 pixel high and wide iceblock as stored in iceblock.jpg.
window.onload=function()
{
Crafty.init(500,500);
Crafty.canvas();
Crafty.sprite(60,"iceblock.jpg",{block : [0,0]});
Crafty.c("iceblock",function(){
init: function(){
this.addComponent("2D, Canvas, Mouse, block");
this.w = 60;
this.h = 60;
}
});
};
for(var i=0;i<5;i++)
{
for(var j=0;j<5;j++)
{
Crafty.e("iceblock").attr({x: i*60,y: j*60})
}
}
The corresponding HTML code is:-
<!DOCTYPE html>
<head>
<script type="text/javascript" src="crafty.js"></script>
<script type="text/javascript" src="assignment.js"></script>
<title>My Crafty Game</title>
</head>
<body>
</body>
</html>
When I open the HTML page, the complete output page is blank.
This is the link to the image.
http://postimage.org/image/ivqfhmjt9/
PS:- Is there a less annoying way to indent our code instead of putting 4 spaces infront of each line? Very time consuming and tedious.
For reference, see this thread https://groups.google.com/forum/?fromgroups#!topic/craftyjs/OkG5rFb3tqo
Or the code here http://jsfiddle.net/cYxeZ/

What are the main components to a javascript slideshow

I edited this post to present it with better clarity of what I'm actually asking.
My confusion was and to some extent still is not being clear on the components that make up a slideshow in javascript.
To the best of my understanding the slideshow has these basic components that makes it work: 1) The array, 2) the preload declaration, 3) the counter, which is the for loop, and 4) the next image function. And of course the onclick button to execute the event. The onclick button calls the next image function. I redid the code. Although, it is not quite working I have no errors and no warnings. Everything looks similar to the tutorials I've been looking at. Any suggestions before I submit my homework. Thank you.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 /DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>slideshow</title>
<script type="text/javascript">
//create array of image objects
var myPic=new Array("photos/picture0.jpg",
"photos/picture1.jpg",
"photos/picture2.jpg",
"photos/picture3.jpg",
"photos/picture4.jpg")
var num=0; //I believe this is my index
//I don't understand why I'm creating a new array here.
//I saw it in two different tutorials
var preLoad=new Array(5)
//Here I'm initializing the counter and preloading the images.
for(i=0;i<myPic.length;i++)
{
preLoad[i]=new Image()//Don't understand this part yet or the next line.
//I saw it in a tutorial
preLoad[i].src=myPic[i]
}
//this is to load the next image, reset the counter and end the loop.
function nextImg()
{
if(num<preLoad.length-1){
num=num+1;
document.getElementById("myImg").src=preLoad[num].src
}
else{
num=0
document.getElementById("myImg").src=preLoad[num].src
}
}
</script>
<!--So far no errors, no warnings.-->
</head>
<body>
<img id="myImg" src="photos/picture0.jpg" width="225" height="225" alt="firt picture" border="3"/>
<input type="button" value="show next picture" onclick="nextImg)" />
</body>
`enter code here`</html>
what's this...?
<form name="show" align: center; />
that looks like style information but it's sitting there naked, and you don't need style on a form anyway, since it's not a displayed thing.
also, you have a bunch of mistakes here, but your biggest one is that you're not understanding how arrays work. Your code isn't doing what you *think it's doing. you're incrementing myPic which isn't an integer, it's an array. What you need to be incrementing is an index IN the array...
myPic = new Array('a','b','c');
myIndex = 0;
var currentLetter = myPic[ index ] ;//currentLetter is now 'a'
index++;
currentLetter = myPic[ index ]; // currentLetter is now 'b'
I'm not sure what you mean by i==[0]... I suspect you mean i == 0? or you're again confusing how looping through arrays works.

Categories