Cannot make addition work - javascript

I am trying to make a button that when clicked adds 200 to the value of the p tag. I have looked up my question and clicked on every result, to no avail.Please help. Whenever I click the button it either prints NaN(Not a Number) or 200200200200200 etc.. I need help so that instead of those 2 mess-ups, it adds 200 each time the button is clicked. (addition not concatenation)
Here is my code:
<button onClick="addPoints()">Click to get points!</button>
<p id="counter"></p>
<script>
function addPoints(){
var id=document.getElementById("counter").innerHTML = parseInt(adding);
var adding = id + 200;
}
There is probably a mess-up I am not aware of. Any help will be greatly appreciated!

Your adding variable was assigned after it is used. This code works:
<button onClick="addPoints()">Click to get points!</button>
<p id="counter"></p>
<script>
function addPoints(){
var x = document.getElementById("counter").innerHTML;
document.getElementById("counter").innerHTML = (isNaN(parseInt(x))?0:parseInt(x)) + 200;
}
</script>
What I did here is the function checks the value of the counter <p> tag. If the content is an integer >= 0, add 200. Otherwise, assign an initial value of 0 before adding 200 so that the contents are added and are not concatenated.

change the sequence of code
function addPoints(){
var adding = parseInt( document.getElementById("counter").innerHTML) + 200;
document.getElementById("counter").innerHTML =adding;
}

Try this
function addPoints(){
var sum=parseInt(document.getElementById("counter").innerHTML);
sum = isNaN(sum) ? 0 : sum;
sum += 200;
document.getElementById("counter").innerHTML = sum;
}

You're trying to use the variable adding in parseInt before actually creating it. Try this:
function addPoints(){
var id=document.getElementById("counter").innerHTML;
var adding = id + 200;
document.getElementById("counter").innerHTML = parseInt(adding);
}

convert id to number
function addPoints(){
var id=document.getElementById("counter").innerHTML = parseInt(adding);
var adding = ((id*1) + 200);
}

Related

Need help understanding onclick and how to continuously subtract from a declared variable

Here is my HTML code:
<button id="remove10" onclick="subtract()">Remove 10</button>
<div id="final-answer">Final answer</div>
Here is my Javascript code:
var startingNumber = 100;
var minus10 = document.querySelector("#remove10");
function subtract() {
startingNumber = startingNumber - 10;
}
minus10.onclick = subtract();
document.querySelector("#final-answer").innerHTML = startingNumber;
My goal is that every time the "Remove 10" button is clicked it subtracts 10 from the initial value of 100 and changes the displayed text to reflect the answer. So 1st click - show 90, 2nd click - show 80, etc.
The code I currently have shows the number as 90 from the start and nothing happens when I click the button. What am I doing wrong here?
There are a couple of issues with your code:
You don't need to assign an onclick handler in both HTML and JS, one is fine. JS is the more common choice.
When assigning an event handler in JS, you must provide a function. subtract() calls the function and assigns its result (which is nothing) to onclick.
You need to update HTML each time subtract is called. The browser doesn't automatically bind startingNumber to the innerHTML of #final-answer.
The code could look like this
var startingNumber = 100;
var minus10 = document.querySelector("#remove10");
function subtract() {
startingNumber = startingNumber - 10;
document.querySelector("#final-answer").innerHTML = startingNumber;
}
// you have to assign a function to "onclick", subtract() calls the function and returns nothing
minus10.onclick = subtract;
document.querySelector("#final-answer").innerHTML = startingNumber;
<button id="remove10">Remove 10</button>
<div id="final-answer">Final answer</div>
I change little your code and add notes inside. Hope that will help you:
var startingNumber = 100; // this is the original number
document.querySelector("#final-answer").textContent = startingNumber; // show it in the container
var minus10 = document.querySelector("#remove10"); // this is the button
minus10.addEventListener('click', subtract); // when clicking the button a function will execute
function subtract() { // this is the function that will execute
startingNumber = startingNumber - 10; // get the number and then subtract 10 from it
document.querySelector("#final-answer").textContent = startingNumber; // write the new number
}
<button id="remove10">Remove 10</button>
<div id="final-answer">Final answer</div>
More side notes:
Instead onclick i use the event listener - read why.
Instead innerHTML i used the textContent - read why.
Enjoy Code!
You aren't assigning the function subtract to onclick, instead you are calling subtract and assigning the value to onclick
Instead try
minus10.onclick = subtract;
You will also need to update innerHtml in your subtract function too, as currently it's only setting it once.

How can I check if input.value is the same as a random number

I want to make a little game where the browser selects a random number between 1 and 10 and the user has to guess which number it is. So I made an input, button and the random function, but every time, also when the inputNumber and the randomNumber are the same, it doesn't output the code I want!
<input type="numebr" id="userInput" />
<button id="button">Sure?</button>
<p id="awnser"></p>
let button = document.getElementById('button');
let input = document.getElementById('userInput').value;
let awnser = document.getElementById('awnser');
button.onclick = function randomFunc() {
var randomnr = Math.floor(Math.random() * 10 +1);
if (input == randomnr) {
awnser.innerHTML = randomnr + '<br> You got it!';
} else {
awnser.innerHTML = randomnr + '<br> Nevermind... idiot :P';
}
}
I tried to solve it's with parseInt
let input = parseInt(document.getElementById('userInput').value);
but it doesn't work. I think its a problem with the input value so that this is not a number rather a string...
Some tips for me?
It's because of what you do with this line:
let input = document.getElementById('userInput').value;
This gets the value when the page loads. when you click on a button, its value is the same as it was when the page got loaded. just move this line into button.onclick function and you should be fine.
Put
let input = document.getElementById('userInput').value;
inside the onclick function

Dynamically increasing font size

I would like to increase the font size of the paragraph as well as the font size of the number in the button.
I copied and pasted my sizer function from StackOverflow (a few alterations) and thought it would work and still can't get it to work. Can someone help?
Since I've spent so much time on just the first part, as a beginner programmer, I'm wondering what I am missing. Does anyone have any ideas from my code or their experience as to what I might be missing?
Thanks as always.
<html>
<button onclick='incrementer(); sizer()' id='count' value=0 />0</button>
<p id='test'>a</p>
<script>
clicks = 0
incrementer = function () {
clicks += 1
click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
}
sizer = function changeFontSize() {
div = document.getElementById("test");
currentFont = div.style.fontSize.replace("pt", "");
div.style.fontSize = parseInt(currentFont) + parseInt(clicks) + "pt";
}
</script>
</html>
Some things here:
I woudn't append two functions to your onclick here. Just append one and call your second function from the first one that gets fired via onclick. That looks a lot more tidy
Don't forget to put var before every variable, without it's not valid JavaScript
I didn't quite understand what you tried with your currentFont variable, so I removed it. It's not necessary and causes the script to not working correctly
<html>
<button onclick='incrementer()' id='count' value=0 />0</button>
<p id='test'>a</p>
<script>
var clicks = 0;
var incrementer = function() {
clicks += 1;
var click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
sizer();
}
var sizer = function changeFontSize() {
var div = document.getElementById("test");
div.style.fontSize = parseInt(clicks) + "pt";
}
</script>
</html>
Here's a from-scratch version that does what you're asking for. I'll point out a few things that I did to help you out.
https://codepen.io/anon/pen/VBPpZL?editors=1010
<html>
<body>
<button id="count">0</button>
<p id="test">
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</p>
</body>
</html>
JS:
window.addEventListener('load', () => {
const button = document.querySelector('#count');
const paragraph = document.querySelector('#test');
const startingFontSize = window.getComputedStyle(document.body, null)
.getPropertyValue('font-size')
.slice(0, 2) * 1;
let clicks = 0;
button.addEventListener('click', () => {
clicks++;
// this is a template literal
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const fontSize = `${startingFontSize + clicks}px`;
button.innerHTML = clicks;
button.style.fontSize = fontSize;
paragraph.style.fontSize = fontSize;
});
});
The code runs when the page is loaded, so we attach an event listener on the window object listening for the load event.
We then store references to the button and the paragraph elements. These are const variables because their values won't change. This also limits their scope to the containing function.
We get the initial font size for the body element, because in this example we aren't explicitly setting a base font in css so we're just using the one for the document. getComputedStyle is a somewhat expensive operation, and in this case we only need to get it in the beginning because it won't change, so we also store it as a const. The value is returned as a string like "16px" but we need the number, hence the slice and multiplying by one to cast the string into a number. parseInt would also do the same thing.
Notice that clicks is defined with let. This means that the variable can be changed. var still works of course, but in modern practices its best to use const and let when declaring variables. This is partly because it forces you to think about what kind of data you're working with.
We add an event listener to the button element and listen for the click event. First, we increment the clicks variable. Then we declare fontSize using a template literal which adds our new clicks count to the startingFontSize and "px" to get a string.
Finally, the innerHTML value of the button element is updated. Then we update the fontStyle property for both elements.
The issue here is that there is no initial value for the fontSize of your <p> tag so div.style.fontSize returns an empty string.
You can use window.getComputedStyle instead of div.style.fontSize and you will get the current fontSize.
There is already a post explaining this method
https://stackoverflow.com/a/15195345/7190518
You don't have an initial font-size style on your <p> tag, so it div.style.fontSize is always empty. Also, best practice is to always use var when introducing new variables in javascript.
One good trick to help debugging things like these is to use console.log() at various points, and see whats coming out in your browser console. I used console.log(div.style.fontSize) and the answer became clear.
Working below after adding <p style='font-size:12px'>a</p>:
<html>
<button style='font-size:12px;' onclick='incrementer(); sizer()' id='count' value=0 />0</button>
<p id='test' style='font-size:12px;'>a</p>
<script>
var clicks = 0
incrementer = function () {
clicks += 1
click = document.querySelector("#count").textContent = clicks;
click.innerHTML = document.getElementById("count").value = document.getElementById('test');
}
var sizer = function changeFontSize() {
var div = document.getElementById("test");
var btn = document.getElementById("count");
var newSize = parseInt(div.style.fontSize.replace("pt", "")) + parseInt(clicks);
div.style.fontSize = newSize + "pt";
btn.style.fontSize = newSize + "pt";
}
</script>
</html>
I don't understand the logic of this solution, but you can simplify it avoiding to use a lot of var (anyway always prefer let or const if you don't need to change), using a single function and writing less code.
function increment(e){
const ctrl = document.getElementById('test');
let current = parseInt(e.dataset.size);
current += 1;
e.innerHTML = current;
e.dataset.size = current;
ctrl.style.fontSize = current + 'pt';
}
<button onclick="increment(this);" data-size="20">20</button>
<p id='test' style="font-size:20pt;">A</p>

How to add a variable multiple times?

I've been trying to make it so that you click a button, and it adds to the amount - done! Well how do you do this multiple times? As in, how do you add 1 each time? This is some of the javascript I have so far:
function stickAmount() {
var y = 1;
var stickNo = document.getElementById("stickNumber");
stickNo.innerHTML = "Sticks: " + y;
}
and the HTML:
<div id="stickNumber" style="margin-left:10px; margin-top:10px;"></div>
var y=1 // move the variable outside of the function
function stickAmount()
{
var stickNo=document.getElementById("stickNumber")
stickNo.innerHTML="Sticks: "+y;
y++ // increment y by 1 every time the function is called
}
DEMO
I've set up a quick jsfiddle to demonstrate how it can be done.
http://jsfiddle.net/benwong/mDTFL/
HTML
Sticks: <span id="NumberOfSticks"></span>
<button id="AddStickButton">Add</button>
Javascript
var numberOfSticks = 1;
var numberOfSticksSpan = document.getElementById("NumberOfSticks");
numberOfSticksSpan.innerHTML = numberOfSticks;
function addStick() {
numberOfSticks++;
numberOfSticksSpan.innerHTML = numberOfSticks;
}
var addStickButton = document.getElementById("AddStickButton");
addStickButton.addEventListener("click", addStick, false);
The main thing is to define the variable for the number of sticks outside of the function which increments the number of sticks.
I moved the "Sticks: " into the HTML since you only need to change the number.
function stickAmount()
{
var y=1;
var stickNo=parseInt(document.getElementById("stickNumber"));
stickNo.innerHTML="Sticks: "+y;
}
setInterval("stickAmount()",500)

javascript height document auto adjust

I got an sidebar which need to adjust to the document size. This works perfectly, its this code:
<script type="text/javascript">
$(document).ready(function(){
$("#sidebar").height( $(document).height() );
});
</script>
But now i got an form in my website which changes with javascript in size when you put in options. So with other words the whole document gets longer when you put in multiple options. But this script doesn't adjust to that so the sidebar just gets cut off when you put in more options.
So with other words is there an possibility to make this script adjust automatically or let the following script rerun the function when it returns:
<script>
treated = new Object();
inputNumber = 1;
function addOne() {
//Create an input type dynamically.
var divElement = document.createElement("div");
var element = document.createElement("input");
inputNumber++;
element.setAttribute("name", "input" +inputNumber);
element.setAttribute("onkeyup", "if (this.value.length > 1 && treated[this.name] != 1){ addOne(); treated[this.name] = '1'; }");
element.setAttribute("id", "productoptiesadd");
var price = document.createElement("input");
price.setAttribute("name", "price" +inputNumber);
price.setAttribute("id", "productoptiesaddprice");
var foo = document.getElementById("japroductopties");
var htag = document.createElement("h7");
htag.innerHTML = "Optie " + inputNumber + ":";
var htags = document.createElement("h7");
htags.innerHTML = " € ";
divElement.appendChild(htag);
divElement.appendChild(element);
divElement.appendChild(htags);
divElement.appendChild(price);
foo.appendChild(divElement);
}
</script>
Hope some1 can help :).
Why not setting #sidebar height property to 100% in your stylesheet ? Is Javascript really necesary ?
Otherwise, just write a function SidebarAutoAdjust() with your first code fragment :
$("#sidebar").height( $(document).height() );
Then all you have to do is calling this function at the end of your addOne() function.

Categories

Resources