Value is not returning form function - javascript

I am a beginner and I am learning JavaScript. I am trying to return a value from a function but I am not getting the value. When I am doing console.log(randomNuber) it is showing undefined. Also, it is not showing anything for the last line of the JavaScript code.
var randomNumberDisplayEl = document.getElementById("random-number-display");
var generateBtnEl = document.getElementById("generate-btn");
function randomDigit() {
var randomEl = parseInt(Math.random() * 10000);
randomNumberDisplayEl.value = randomEl;
return randomEl;
}
var randomNumber = generateBtnEl.addEventListener("click", randomDigit);
console.log("Random Number is:", randomNumber);
console.log(randomNumberDisplayEl.value);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pin Generator</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<!-- <link rel="stylesheet" href="style.css"> -->
<link rel="stylesheet" href="https://res.cloudinary.com/djz3p8sux/raw/upload/v1628938996/StackOverflow/style_til9dq.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="pin-generator half-width">
<input class="form-control" id="random-number-display" type="text">
<button class="generate-btn" id="generate-btn">Generate Pin</button>
</div>
</div>
</div>
<div class="notify-section pb-3" id="notify-section">
<p class="notify" id="notify-wrong">❌ Pin Didn't Match, Please try again</p>
<p class="notify" id="notify-right">✅ Pin Matched... Secret door is opening for you</p>
</div>
</div>
<script src="./main.js"></script>
</body>
</html>
Why I am getting the value of randomNumber? Also not getting anything for the last line randomNumberDisplayEl.value.
Actually, I need the randomNumber as a global variable so that I can use it anywhere in the program.
How can I get the value of randomNumber outside of function randomDigit?
Help me please. Thank you.

There seems to be a bit of confusion between what is an element and what is an 'ordinary' variable value, like a number in this case.
In this code:
var randomNumberDisplayEl = document.getElementById("random-number-display");
var generateBtnEl = document.getElementById("generate-btn");
function randomDigit() {
var randomEl = parseInt(Math.random() * 10000);
randomNumberDisplayEl.value = randomEl;
return randomEl;
}
var randomNumber = generateBtnEl.addEventListener("click", randomDigit);
console.log("Random Number is:", randomNumber);
console.log(randomNumberDisplayEl.value);
randomNumberDIsplayEl and generateBtnEl both correctly are elements (hence the El at the end).
However randomEl is set to be a random number. I suggest this be renamed, say to what it is: randomNumber.
Then in the above code, randomNumber is assigned from something (an addEventListener) that doesn't return anything. What we need to do is add the event listener and then in the function called when the user clicks (randomDigit) that is when the random number can be looked at.
The function is named as if it were getting a digit, so I've renamed it to what it is doing, getRandomNumber to try to make the sequence of events clearer.
So the above code becomes:
var randomNumber; //make it global
var randomNumberDisplayEl = document.getElementById("random-number-display");
var generateBtnEl = document.getElementById("generate-btn");
function getRandomNumber() {
randomNumber = parseInt(Math.random() * 10000);
randomNumberDisplayEl.value = randomNumber;
console.log("Random Number is:", randomNumber);
console.log(randomNumberDisplayEl.value);
return randomEl;
}
generateBtnEl.addEventListener("click", getRandomNumber);

Try this
var notifyWrongEl = document.getElementById("notify-wrong");
var notifyRightEl = document.getElementById("notify-right");
var randomNumberDisplayEl = document.getElementById("random-number-display");
var generateBtnEl = document.getElementById("generate-btn");
// Notifications Hide
notifyWrongEl.style.display = "none";
notifyRightEl.style.display = "none";
function randomDigit() {
var randomEl = parseInt(Math.random() * 10000);
randomNumberDisplayEl.value = randomEl;
return randomEl;
}
let randomNumber = 0;
generateBtnEl.addEventListener("click", function(){
randomNumber = randomDigit()
console.log("Random Number is:", randomNumber);
console.log(randomNumberDisplayEl.value);
});

You can declare randomNumber before the randomDigit() function, and set its value to the random number, generated by the function.
Note: randomNumber will be undefined before the first button click. You can initialize it with some default value, if you want to.
var randomNumberDisplayEl = document.getElementById("random-number-display");
var generateBtnEl = document.getElementById("generate-btn");
var randomNumber;
function randomDigit() {
var randomEl = parseInt(Math.random() * 10000);
randomNumberDisplayEl.value = randomEl;
randomNumber = randomEl;
}
generateBtnEl.addEventListener("click", () => {
randomDigit();
/* For Logging purposes*/
console.log("Random Number is:", randomNumber);
console.log(randomNumberDisplayEl.value);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pin Generator</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<!-- <link rel="stylesheet" href="style.css"> -->
<link rel="stylesheet" href="https://res.cloudinary.com/djz3p8sux/raw/upload/v1628938996/StackOverflow/style_til9dq.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="pin-generator half-width">
<input class="form-control" id="random-number-display" type="text">
<button class="generate-btn" id="generate-btn">Generate Pin</button>
</div>
</div>
</div>
<div class="notify-section pb-3" id="notify-section">
<p class="notify" id="notify-wrong">❌ Pin Didn't Match, Please try again</p>
<p class="notify" id="notify-right">✅ Pin Matched... Secret door is opening for you</p>
</div>
</div>
<script src="./main.js"></script>
</body>
</html>

It seems you had the JS code in the CSS section, I put it in the JS section and removed the useless code in the end (addEventListener doesn’t return what the fuction does, the randomNumber should be stored from the function.) and it works. In order to generate 4-digit codes, it needs to generate numbers greater or equal to 1000 or to add leading zeroes.
var randomNumberDisplayEl = document.getElementById("random-number-display");
var generateBtnEl = document.getElementById("generate-btn");
var randomNumber;
function randomDigit() {
randomNumber = parseInt(Math.random() * 9000 + 1000);
randomNumberDisplayEl.value = randomNumber;
}
generateBtnEl.addEventListener("click", randomDigit);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Pin Generator</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<!-- <link rel="stylesheet" href="style.css"> -->
<link rel="stylesheet" href="https://res.cloudinary.com/djz3p8sux/raw/upload/v1628938996/StackOverflow/style_til9dq.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="pin-generator half-width">
<input class="form-control" id="random-number-display" type="text">
<button class="generate-btn" id="generate-btn">Generate Pin</button>
</div>
</div>
</div>
<div class="notify-section pb-3" id="notify-section">
<p class="notify" id="notify-wrong">❌ Pin Didn't Match, Please try again</p>
<p class="notify" id="notify-right">✅ Pin Matched... Secret door is opening for you</p>
</div>
</div>
<script src="./main.js"></script>
</body>
</html>

Related

I have created a number guessing game from 1 to 10, Here is the Js code but i am unable to get the output

I have created a number guessing game from 1 to 10, Here is the Js code but i am unable to get the output.
Here is my code:
var enterButton = document.getElementById('enterButton');
var againButton = document.getElementById('againButton');
var output = document.getElementById('outputText');
var randomNumber = Math.ceil(Math.random() * 10);
function checkNumber() {
var input = document.getElementById('userInput').value;
if (input == randomNumber) {
alert.innerHTML = "Your guess is right " + "," + ",it was " + randomNumber;
} else if (number > randomNumber && input < 10) {
alert.innerHTML = "Your guess is to high";
} else if (input < randomNumber && input > 1) {
alert.innerHTML = "Your guess is too low ";
} else if (isNaN(input)) {
alert.innerHTML = "Invalid operator";
}
enterButton.addEventListener('click', checkNumber);
againButton.addEventListener('click', function () {
})
}
Here it the html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="sylesheet" href="index.css" />
</head>
<body>
<script src="script.js">
</script>
</body>
<div id="container">
<p> Guess a number between 1-10</p>
<p id="outputtext"> Enter the number below </p>
<input id="userInput">
<button id="enterButton">Enter</button>
<button id="aginButton">Try again</button>
</div>
</html>
There a couple of issues in your code, first in the html code, you got the id of again button wrong, it should be like this:
<button id="againButton">Try again</button>
Then in the JS code, you should move the two addEventListener() methods out of the checkNumber() function definition. Most importantly, you set the input variable to be the value of the input html element. The value property returns string, and then you compare randomNumber with a string which will not work as expected.
Also, the alert.innerHTML will not work. alert() is a global method which will accepts a string type as its parameter. Please see the JS code corrected below:
var enterButton = document.getElementById('enterButton');
var againButton = document.getElementById('againButton');
var output = document.getElementById('outputText');
var randomNumber = Math.ceil(Math.random() * 10);
function checkNumber() {
var input = parseInt(document.getElementById('userInput').value);
if (input === randomNumber) {
window.alert("Your guess is right it was " + randomNumber)
} else if (input > randomNumber && input < 10) {
window.alert("Your guess is to high");
} else if (input < randomNumber && input > 1) {
window.alert("Your guess is too low ");
} else if (isNaN(input)) {
window.alert("Invalid operator");
}
}
enterButton.addEventListener('click', checkNumber);
againButton.addEventListener('click', function () {
})
You should also put your script tag right before the ending </body> tag for it to be able to do its tasks on the DOM elements. Take a look here:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="sylesheet" href="index.css" />
</head>
<body>
<div id="container">
<p> Guess a number between 1-10</p>
<p id="outputtext"> Enter the number below </p>
<input id="userInput">
<button id="enterButton">Enter</button>
<button id="againButton">Try again</button>
</div>
<script src="script.js"></script>
</body>
</html>
There were a few errors in your script. Check out this fixed version.
UPDATE
I now put the <script> element ahead of the <body> element to demonstrate the necessitiy of the window.onload=function(){...}. My whole script is now placed within this function as otherwise, the DOM elements the script refers to, would not yet exist.
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="sylesheet" href="index.css" />
<script>
window.onload=function(){
const [form1,againButton,output,inp]="container,againButton,outputText,userInput".split(",")
.map(id=>document.getElementById(id)), setrndm=_=>randomNumber=Math.ceil(Math.random()*10);
var randomNumber;
setrndm();
form1.addEventListener('submit', checkNumber);
againButton.addEventListener('click', setrndm);
function checkNumber(ev) {
ev.preventDefault(); inp.select();
var input = inp.value;
if (input == randomNumber) {
console.log("Your guess is right, it was " + randomNumber);
} else if (input > randomNumber && input < 11) {
console.log("Your guess is to high");
} else if (input < randomNumber && input > 0) {
console.log("Your guess is too low ");
} else if (isNaN(input)) {
console.log("Invalid operator");
}
}
};
</script>
</head>
<body>
<form id="container">
<p> Guess a number between 1-10</p>
<p id="outputtext"> Enter the number below </p>
<input id="userInput">
<button id="enterButton">Enter</button>
<button type="button" id="againButton">Try again</button>
</form>
</body>

How can I change the display a message depending on which number the user has selected?

I want when somebody input a number lower than 4.2, my app shows message as result, but i can't make it happen.
I already tried with return.
JS code
let resultEl = document.getElementById("results")
let numberEl = document.getElementById("number__select")
let message = "mAs: 0.5 y kV: 1.0"
function calculate() {
if (numberEl <= 4.2) {
resultEl.textContent = message;
} else {
resultEl.textContent = "error"
}
}
HTML code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styleRx.css"/>
<script src="Rxappjs.js"></script>
<title>HVDN Rx app</title>
</head>
<body>
<div class="container">
<header>
<h1>Valoraciones de Rx</h1>
</header>
<div class="box">
<form action="">
<div class="values">
<label for="peso" id="peso__label">Peso</label>
<input class="text__input" type="number" step="0.1" id="number__select" placeholder="Peso"
min="0" required>
</div>
<button id="calcular" onclick="calculate()">Calcular</button>
</form>
<p id="results"></p>
</div>
</div>
</body>
</html>
You have the variable numberEl set to an html element and therefor it will never be less than or equal too 4.2. Try to get the value of that element instead:
let resultEl = document.getElementById("results")
let numberEl = document.getElementById("number__select")
let message = "mAs: 0.5 y kV: 1.0"
function calculate() {
if (numberEl.value <= 4.2) {
resultEl.textContent = message;
} else {
resultEl.textContent = "error"
}
}

Range addEventListner Input Updating too frequently

I am new to JavaScript for context.
I want to have a web page where the user has a base number, which is an input and can have unlimited subtractors, or "sources", that will bring the number down. It's like the user is listing all of his or her sources to pay for something expensive. Each source will have a name and a range, which goes from -100 to 100.
The problem with it is that it takes every change in input as a potential source, but I want only the value of the ranges to be sourced. In other words, if the user has added five ranges, then I only want there to be five subtractors/sources.
Is there anything I could do to make this change happen? It also may be helpful to know that when I change the event listener to 'mouseDown' the same thing happens.
Here is everything I have written.
const addBtn = document.querySelector(".solvePlusLogo")
function addSolvr() {
solvContain = document.querySelector('.solveContainer')
const solvDiv= document.createElement('div');
solvContain.appendChild(solvDiv);
const solvLabel = document.createElement('input');
solvDiv.appendChild(solvLabel);
const solvRange = document.createElement('input');
solvRange.type = "range";
solvRange.className = "range"
solvDiv.appendChild(solvRange);
}
addBtn.addEventListener('click', addSolvr)
let full = document.querySelector("#numInput").value
document.addEventListener('input', function(event) {
if(event.target.matches(".range")) {
const subtractors = []
subtractors.push(event.target.value)
for(let x of subtractors) {
full -= x
}
document.querySelector("#numDisplay").innerHTML = full
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<input type="number" id="numInput">
<h3 id="numDisplay">
$0
</h3>
<div class="solveContainer" style="font-family: 'IBM Plex Mono', momnospace;">
<div class="solveIntro">
<button class="solvePlusLogo">Add Source
</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Every time the range changes, you're subtracting its current value from full. But full has previously had a different range value subtracting, so these subtractions are accumulating.
You need to get the current value of #numInput and subtract the range value from it.
Your subtractors array will just contain the value of the current range input. You need to loop over all the ranges and combine them.
const addBtn = document.querySelector(".solvePlusLogo")
function addSolvr() {
solvContain = document.querySelector('.solveContainer')
const solvDiv = document.createElement('div');
solvContain.appendChild(solvDiv);
const solvLabel = document.createElement('input');
solvDiv.appendChild(solvLabel);
const solvRange = document.createElement('input');
solvRange.type = "range";
solvRange.className = "range"
solvDiv.appendChild(solvRange);
}
addBtn.addEventListener('click', addSolvr)
document.addEventListener('input', function(event) {
if (event.target.matches(".range")) {
let full = document.querySelector("#numInput").value
const subtractors = document.querySelectorAll(".range");
subtractors.forEach(subtractor => full -= subtractor.value)
document.querySelector("#numDisplay").innerHTML = full
}
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<input type="number" id="numInput">
<h3 id="numDisplay">
$0
</h3>
<div class="solveContainer" style="font-family: 'IBM Plex Mono', momnospace;">
<div class="solveIntro">
<button class="solvePlusLogo">Add Source
</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>

Javascript object method is not a function

I have been searching here and haven't found something that quite matches, of course correct me if I'm wrong. This seems simple but I cannot see the reason.
function Dice() {
if (!(this instanceof Dice)) {
return new Dice();
};
this.sides = 6
};
Dice.prototype.setUpDieForHTML = function(roll) {
const die = [
'C:\\projects\\apoc\\img\\perspective-dice-six-faces-one.svg',
'C:\\projects\\apoc\\img\\perspective-dice-six-faces-two.svg',
'C:\\projects\\apoc\\img\\perspective-dice-six-faces-three.svg',
'C:\\projects\\apoc\\img\\perspective-dice-six-faces-four.svg',
'C:\\projects\\apoc\\img\\perspective-dice-six-faces-five.svg',
'C:\\projects\\apoc\\img\\perspective-dice-six-faces-six.svg'
];
const img = document.createElement('img');
const dice = $('.dice');
img.classList.add('dice-size');
img.setAttribute('src', die[roll]);
dice.append(img);
}
Dice.prototype.dieRoll = function() {
let result = 1 + Math.floor(Math.random() * 6);
switch (result) {
case 1:
this.setUpDieForHTML(result);
break
case 2:
this.setUpDieForHTML(result);
break
case 3:
this.setUpDieForHTML(result);
break
case 4:
this.setUpDieForHTML(result);
break
case 5:
this.setUpDieForHTML(result);
break
default:
this.setUpDieForHTML(result);
break
}
}
module.exports = {
Dice
};
When I instantiate the object and call dieRoll() I get setUpDieForHTML is not a function. I have moved the code around, changed to a class, run directly in Node REPL it seems to recognize the functions. Also in the dev tools of chrome the instance object has the functions until called.
index.js
'use strict'
const die = require('./js/gamePieces/dice')
const newDie = new die.Dice()
$(() => {
debugger
$('.die-start-icon').on('click', newDie.dieRoll)
})
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Fallout Meeples</title>
<!-- <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Do not add `link` tags-->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico">
<!-- Do not add `script` tags-->
<script src="public/vendor.js" type="text/javascript" charset="utf-8" defer></script>
<script src="public/application.js" type="text/javascript" charset="utf-8" defer></script>
</head>
<body>
<main id="apoc" class="game-area">
<section class="player-start-area border yellow">
<h2>Player One</h2>
<section id="playerOne-dice">
<div class="dice">
<img class="die-start-icon dice-size" src="./assets/img/perspective-dice-six-faces-random.svg">
<!--C:\\projects\\apoc\\assets\\img\\perspective-dice-six-faces-random.svg-->
</div>
</section>
</section>
<section class="player-start-area border blue">
<h2>Player Two</h2>
<section id="playerTwo-dice">
<div class="dice"></div>
</section>
</section>
<div class="dice"></div>
</main>
<!-- <script src="./assets/scripts/js/gamePieces/dice.js" type="text/javascript"></script> -->
</body>
</html>
I know there are some other issues in my code but this one thing I couldn't figure out.

NaN returned when running a function to change a variable

I am trying to make a clicker game in HTML and JavaScript, and when I click the button to give me money, nothing happens. I tried printing it to the console, and it returned as NaN once, and once I clicked the button again, nothing happened. Here is the code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="icon" type="image/png" href="http://marcopolo0306.github.io/content/images/icon.png">
</head>
<body>
<a class="clicker" id="clicker" href="#"> Click for Money </a>
<div class="main-content">
<h2 id="para">Money: 0</h2>
<script type="text/javascript">
document.getElementById("clicker").onclick= update(2);
//document.cookie = "money="+money, time() + (10 * 365 * 24 * 60 * 60);
var money = parseFloat(0);
function update (amount)
{
console.log(parseFloat(amount))
money += parseFloat(amount);
document.getElementById("para").innerHTML="Money: " + parseFloat(amount);
return false;
}
</script>
</div>
</body>
</html>
I don't see any NaN(when I run your code) but found one mistake and that is document.getElementById("clicker").onclick= update(2); here you are not assigning function to onclick but you calling function and return value of function(which is undefined for above case as we are not returning anything) is assigned to onclick(which is undefined). o assign function do following document.getElementById("clicker").onclick= function(){update(2);}
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="icon" type="image/png" href="http://marcopolo0306.github.io/content/images/icon.png">
</head>
<body>
<a class="clicker" id="clicker" href="#"> Click for Money </a>
<div class="main-content">
<h2 id="para">Money: 0</h2>
<script type="text/javascript">
document.getElementById("clicker").onclick= function(){ update(2) };
//document.cookie = "money="+money, time() + (10 * 365 * 24 * 60 * 60);
var money = parseFloat(0);
function update (amount)
{
console.log(parseFloat(amount))
money += parseFloat(amount);
console.log(money);
document.getElementById("para").innerHTML="Money: " + parseFloat(amount);
return false;
}
</script>
</div>
</body>
</html>
This line should be as follows:
document.getElementById("clicker").onclick= update
...not...
document.getElementById("clicker").onclick= update(2)
As you've written it, update is only called once, with a value of 2. You're getting NaN because update is called before you've zeroed money.
By the way, this is sufficient:
var money = 0;
There's nothing to be gained by adding parseFloat in there.
You're assigning the call to the update function as the onclick event handler.
If you want to send an argument, you should bind it in the event handler like so:
document.getElementById("clicker").onclick = update.bind(this, 2);
A few things wrong here.
As others pointed out you need to use an anonymous function on the onclick and pass the parameter to update in there
You should wrap only the number in a span to make the code parse the number easier in the update function.
You were never incrementing the previous value, only incrementing from 0 each time update is called. you need to get the previous value, parse it, and then add to it.
document.getElementById("clicker").onclick = function() {
update(2)
};
//document.cookie = "money="+money, time() + (10 * 365 * 24 * 60 * 60);
var para = document.getElementById("para");
var money = document.getElementById("money");
function update(newAmount) {
var oldMoney = parseFloat(money.textContent);
var newMoney = oldMoney + parseFloat(newAmount);
money.innerHTML = parseFloat(newMoney);
}
<a class="clicker" id="clicker" href="#"> Click for Money </a>
<div class="main-content">
<h2 id="para">Money: <span id="money">0</span></h2>
</div>
Rather than grabbing the element from the DOM and assigning the event, it might be advisable to explicitly wire the function on the onclick event in the HTML itself.
Anyway, what you were doing was assigning a function call to an event. Anytime you have parentheses "()" after a function name, it gets invoked. Rather you have to assign the body of a function, which gets executed. For instance, your code ought to be ->
document.getElementById("clicker").onclick= function () {update(2)};
Here is a code that might be working as you would have expected
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="icon" type="image/png" href="http://marcopolo0306.github.io/content/images/icon.png">
</head>
<body>
<a class="clicker" id="clicker" onclick="update(2)" href="#"> Click for Money </a>
<div class="main-content">
<h2 id="para">Money: 0</h2>
<script type="text/javascript">
var money = parseFloat(0);
function update (amount)
{
console.log(parseFloat(amount))
money += parseFloat(amount);
document.getElementById("para").innerHTML="Money: " + parseFloat(amount);
return false;
}
</script>
</div>
</body>
</html>
Since you are incrementing the money variable it would seem that you also want that value to display rather than the amount being passed in:
document.getElementById("para").innerHTML="Money: " + parseFloat(money);
Not...
document.getElementById("para").innerHTML="Money: " + parseFloat(amount);
<head>
<link rel="stylesheet" href="style.css">
<link rel="icon" type="image/png" href="http://marcopolo0306.github.io/content/images/icon.png">
</head>
<body>
<a class="clicker" id="clicker" onclick="update(2)" href="#"> Click for Money </a>
<div class="main-content">
<h2 id="para">Money: 0</h2>
<script type="text/javascript">
//document.cookie = "money="+money, time() + (10 * 365 * 24 * 60 * 60);
var money = parseFloat(0);
function update (amount)
{
console.log(parseFloat(amount))
money += parseFloat(amount);
console.log(money);
document.getElementById("para").innerHTML="Money: " + money;
return false;
}
</script>
</div>
</body>
document.getElementById("clicker").onclick= function(){ update(2) };
//document.cookie = "money="+money, time() + (10 * 365 * 24 * 60 * 60);
var money = parseFloat(0);
function update (amount){
money += amount;
document.getElementById("para").innerHTML="Money: " + money;
return false;
}
<html>
<head>
<link rel="stylesheet" href="style.css">
<link rel="icon" type="image/png" href="http://marcopolo0306.github.io/content/images/icon.png">
</head>
<body>
<a class="clicker" id="clicker" href="#"> Click for Money </a>
<div class="main-content">
<h2 id="para">Money: 0</h2>
</div>
</body>
</html>

Categories

Resources