I am newbie with javascript and I wrote a very simple program to display something using function and alert. Here is my code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script>
var balance = 10500;
var cameraOn = true;
function steal(balance, amount){
cameraOn = false;
if (amount < balance) {
balance = balance - amount;
}
return amount;
cameraOn = true;
}
var amount = steal(balance, 1250);
alert("Criminal: you stole " + amount + "!");
</script>
</body>
</html>
The code is ok, when I ran it, it display "Criminal: you stole 1250!" as I expected. But, my problem is, in my code as you can see, there is a code cameraOn = true; I do not know why I must write this code ( I copy this code from the book I studied ).
When I made this line to be referenced, the result did not change. So, I thought that this code is not necessary ?
Could you please give me some ideas for me with this problem ? Thank you very much.
It's not executed since it's written after the "return" keyword.
So yes, you can (you should) delete this line.
Related
followed a tutorial just with different layout and names and still can't seem to find whats wrong?
<!DOCTYPE html>
<html>
<head>
<script>
function myrandom() {
var x = math.floor((math.random() * 10) + 1);
document.getElementById("rand").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myrandom()">Generate</button>
<p id='rand'></p>
</body>
</html>
Reason :
What you are doing wrong is that you are using math instead of Math. JavaScript is case sensitive and Math is defined while math is not.
Corrected :
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<button onclick="myrandom()">Generate</button>
<p id='rand'></p>
<script>
var myrandom = () => {
var x = ~~((Math.random() * 10) + 1);
document.getElementById("rand").innerHTML = x;
}
</script>
</body>
</html>
Also please note that it is better that you write the JS code at the end of the body tag and the script tag is the last one in the body tag.
Note :
Note that I edited the snippet provided by you.
The following edits were made
The script tag was moved at the end of body tag
I changed the function and used arrow syntax instead of normal declaration
Changed Math.floor into bitwise ~~
Resources :
Stack overflow script tag
W3 schools script tag
bit wise operators mozilla
bit wise operators W3 schools
Arrow function mozilla
You have a typo, You need to capitalize the first letter of math -> Math.
<!DOCTYPE html>
<html>
<head>
<script>
function myrandom() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("rand").innerHTML = x;
}
</script>
</head>
<body>
<button onclick="myrandom()">Generate</button>
<p id='rand'></p>
</body>
</html>
I'm new to JavaScript and already encountered a problem. When I run the code and the browser pops up, it[browser] does not show anything. What I have is the testMethod.js file with one method:
function testMethod(num1, num2){
var value = num1 + num2;
return value;
}
and an HTML file from where I'm trying to run:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title> My JavaScript</title>
<script language = "javascript" src = testMethod.js"></script>
</head>
<body>
<script language = "javascript" type = "text/javascript">
// var getValue = testMethod(2,3);
document.write("The result is " + testMethod(5,3));
</script>
<noscript>
<h3> This site requires JavaScript</h3>
</noscript>
</body>
</html>
The code is not implementing the result at all. It shows only a blank page browser.
It seems you have a quote missing in the html, it should say src="testMethod.js" where you are including the script in the first place.
Making my own version of cookie clicker for the lols at school, having some problems;
<!DOCTYPE html>
<html>
<head>
<title>Patrick Clicker</title>
<script>
var patricks = parseInt(localStorage.getItem("patrickcount"));
function increment(n) {
localStorage.setItem("patrickcount", patricks + n);
document.getElementById("patrickcounter").innerHTML = "Patricks: " + patricks;
}
</script>
</head>
<body>
<img src="patrick.jpg" onclick="increment(1)">
<p id="patrickcounter">
Patricks: 0
</p>
</body>
</html>
When I click my face, it says "Patricks: NaN"
I know what NaN means, but I don't know why the error is being caused.
Any help would be appreciated.
It won't work initially because you don't have a value at first in localStorage.
You can do this :
var patricks = parseInt(localStorage.getItem("patrickcount"))||0;
Do you intentionally display the value before increment ? If that's not your intent, change your function to
function increment(n) {
patricks += n;
localStorage.setItem("patrickcount", patricks);
document.getElementById("patrickcounter").innerHTML = "Patricks: " + patricks;
}
If you want the page to show the right value right before you click, add this at the end of the body :
<script>increment(0)</script>
I'm learning a bit HMTL5 to prepare to the 70-480 exam. I'm trying to do some javascript code. It looks something like this:
function inchestometers(inches) {
if (inches < 0)
return -1;
else {
var meters = inches / 39.37;
return meters;
}
}
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
and I have such html code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Htnl 5 test</title>
<script src="script/test.js"></script>
</head>
<body>
<p id="hello">Hello</p>
</body>
</html>
In my VS 2012 i have used the Asp.net Empty Web application project and added the Js file and also the html file. The problem is that The function runs properly without any exeptions. This function is taken from here: http://msdn.microsoft.com/en-us/library/cte3c772(v=vs.94).aspx
But whem I'm trying to run the code where I'm getting the document element it' crashint with the error like in the subject. What I've investigated is that the hello gets the null value. I've also tried the code thaken from here:
http://msdn.microsoft.com/en-us/library/yfc4b32c(v=vs.94).aspx - the example with the div. I have the same effect.
What is wrong? I know that there were simmilar subjects but I can't seem to find one matching to mine. Thank you kindly for your help.
Regards
Rafal
you are getting a problem because your javascript code is running before the element
<p id="hello">
is defined.
the simplest solution is to include your script at the end of the body section instead of in the head section but this would cause the document.write call to occur after the rest of the content.
another solution would be to place the code inside two functions like this
function do_conversion() {
var inches = 12;
var meters = inchestometers(inches);
document.write("the value in meters is " + meters);
}
function say_hello() {
var hello = document.getElementById("hello");
hello.firstChild.nodeValue = "Hello World";
}
then change the body section like this
<body onload='say_hello()'>
<script>
do_conversion();
</script>
<p id="hello">Hello</p>
</body>
I have a simple array with x number of items. I am displaying them individually via a link click... I want to update a number that say 1 of 10. when the next one is displayed i want it to display 2 of 10 etc...
I have looked all around and my brain is fried right now... I know its simple I just cant get it out.
<!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" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Page Title</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" charset="utf-8"/>
<script type="text/javascript">
var quotations = new Array()
quotations[0]= "abcd"
quotations[1]= "efgh"
quotations[2]= "ijkl"
quotations[3]= "mnop"
quotations[4]= "qrst"
quotations[5]= "uvwx"
quotations[6]= "yzab"
numQuotes = quotations.length;
curQuote = 1;
function move( xflip ) {
curQuote = curQuote + xflip;
if (curQuote > numQuotes)
{ curQuote = 1 ; }
if (curQuote == 0)
{ curQuote = numQuotes ; }
document.getElementById('quotation').innerHTML=quotations[curQuote - 1];
}
var curPage = curQuote
</script>
</head>
<body>
<div id="quotation">
<script type="text/javascript">document.write(quotations[0]);</script>
</div>
<div>
<p>GO back
<script type="text/javascript">document.write(curPage + " of " + numQuotes)</script>
GO FORTH</p>
</div>
</body>
</html>
Edit: curQuote is not updating dynamically... it stays at '1' when next is clicked.
In your code, curQuote is already the value you want. I rewrote everything to clean it up and show some better logic/syntax. Note that ideally you would be attaching the click handlers via DOM methods and not using inline handlers, but for simplicity I've left it that way here.
Working version viewable here: http://jsbin.com/irihu3/2
<html>
<head>
<title>Quotations</title>
<script type="text/javascript" charset="utf-8">
var quotations = ["hi", "how", "are", "you", "today", "good", "sir"],
lastIndex = quotations.length - 1,
currentIndex = 0;
function move(xflip) {
currentIndex = currentIndex + xflip;
if (currentIndex > lastIndex) {
currentIndex = 0;
} else if (currentIndex < 0) {
currentIndex = lastIndex;
}
document.getElementById('quotation').innerHTML = quotations[currentIndex] + " (Quote #" + (currentIndex + 1) + ")";
return false;
}
</script>
</head>
<body>
<div id="quotation">hi (Quote #1)</div>
<a onclick="move(-1);">Prev</a>
<a onclick="move(1)">Next</a>
</body>
</html>
Some things to note:
Always declare variables with the var keyword or you create global variables.
You can combine multiple variable declarations into one statement by separating them with commas. It's good practice to stick to one var statement and to put it at the top of your code/function.
All you really need to keep track of here is the current index of the array, not the quote itself. It's also not important how long the array is, just what the last index is. As such, in my code I am using currentIndex and lastIndex instead of curQuote and numQuotes.
Using return false; at the end of your function will suppress the default action when clicking on a hyperlink (not following the link). This is what you want in this case, because you're using a hyperlink to trigger behavior on the page and not actually navigating to another page.
You're making a lot of beginner mistakes in your JavaScript but it seems as if curQuote has the value you want, no?
Tips:
You can declare an array as such: var array = [1,2,3,4,5,6,7];
Terminate statements with a semi-colon.
Use var keyword for local variables.
Don't put braces around one line if statements bodies.
Use indentation properly to make the code readable.
Try this
var curPage = quotations[curQuote];