increasing a number inside of a mouseClicked funtion - javascript

I have a code where I draw an object when the mouse is clicked using mouseClicked = function(){} and then I need to have a number to show how many objects have been drawn. the problem is that the number won't increase. what do I do?

Rather than declaring and incrementing a global variable - you could set the count as a HTML 5 data attribute on the button and then on clicking the button, get the data attribute value, increment it and update the display and the new count on the button.
Note that data-attributes are always strings - hence the need for the parseInt() method, though if I was being a purist - I would have put the radix in as well, but that defaults to 10 - so no need in this case.
It is always better to avoid global variable when possible and data attributes offer a very conveniant way of storing local data.
Thanks to #Sven.hig for the skeletn code of the solution - which I then modified to my approach.
var res=document.getElementById("res")
var btn=document.getElementById("btn")
btn.addEventListener("click",()=>{
const newCount = parseInt(btn.getAttribute('data-count'))+1;
res.textContent = newCount;
btn.setAttribute('data-count', newCount)
})
<div id="res"></div>
<button id="btn" data-count="0">Draw</button>

Here is a simple example that will give you an idea about how to increment a counter
var res=document.getElementById("res")
var btn=document.getElementById("btn")
var count=1
btn.addEventListener("click",()=>{
res.textContent=count
count++
})
<div id="res"></div>
<button id="btn">Draw</button>

If the count variable is defined inside the mouseClicked function as the title say, you are recreating it in every mouseClick. In this case, you should define it outter the function with value = 0 and, inside the function, sum 1 to that value. Anyway, like the comments say, it's necessary that you include the code to your question to give a better answer.

this is an easy way to counter the clicks on a html document.
let counter = 0;
document.onclick = () => {
counter++;
console.log(counter);
}

Related

i need to increment a number in a classList template string javascript

hello friends I got a hard one and I'm a bit in a pickle
in my blackjack game I create images(of the cards) and the values come from the .PNG name from a list in an object. what I want to do is be able to create a class on those images to be able to use the classList.contain() method in a other function. it seems to work but the number doesn't increment every time I call the function. All the cards have the same class.
function showCard(activePlayer, card) {
if (activePlayer.score <= 20){
let cardImage = document.createElement("img")
function incrementNumber(number){
number = number++
return number
}
//increment the number of the class
cardImage.classList.add(`images${incrementNumber()}`)
cardImage.src = `images/${card}.png`
document.querySelector(activePlayer["div"]).appendChild(cardImage)
hitSound.play()
}
}
I know i most likely forgot a simple thing but i cannot put my finger on it.
I added a number in the ${incrementNumber(1)} still keeps giving me the same images class for all images. thank you for all you're help!
The ++ (increment) operator can be confusing sometimes.
In your case, you are using it, but you are also assigning its return value back to the number. The easiest solution is not doing that assignment (changing number = number++ for just number++)
It also looks like number should be a global variable, not a parameter passed to the incrementNumber function.
The more interesting part to the problem though, is why the code does not work. This is due to how the ++ operator works. When you place it after a variable name (eg number++) JavaScript will effectively do this:
var temp = number;
number = number + 1;
return temp;
It increments the number variable by 1, but it returns the previous value of the variable. In your case, when assigning the result of number++ back to number, the increment operation will basically be cancelled out.
Also, note that you can place the ++ operator before a variable name (like ++number). This will not return the original value of the variable, instead returning the new (incremented) value.
Add a global variable to your scope named number and set it to one. Then replace number = number++ with number++.

How to have a variable increase over time (JS)

i was wondering how to make a variable go up over time, ive tried to do this -->
var i = 1;
var c = document.getElementById("click");
function workers() {
if (click >= workers*50000)) {
click += -(workers*50000)
click += i++
c.innerHTML = click;
}
}
but it hasnt worked, how do i fix this?
you could do this
let i = 0;
// instead of 2000 insert the frequency of the wanted update (in milliseconds)
const incrementInterval = setInterval(() => i++, 2000)
// when you want it to stop it
clearInterval(incrementInterval)
anyway, i don't really understand how the code supplied with the question has anything to do with it
You have an element and a variable 'click', which tells me you're really not wanting to grow over time per se, but rather grow with every click.
Another difficulty is finding out what you're trying to do with multiplying by 50000. I am assuming you are trying to reset the count after 50000.
One big thing you're missing is the actual association of the click event to your 'click' HTML element. Below, I'm using addEventListener to do that. From there, I'm resetting the counter to '1' if 'i' goes above '5' (I use 5 just to show the reset in a reasonable number of clicks). Then I take the value of 'i' and put it into the innerHTML label of the element that triggered the event.
var i = 1;
document
.getElementById("click")
.addEventListener('click', function(e) {
if (i > 5)
i = 1;
e.target.innerHTML = `click: ${i++}`;
})
<div id='click'>click<div>
Define your question better. What is your goal? What has your code achieved? What result are you getting and how is it different than your expectations? What is 'i' meant to be used for? How does it interact with the function? Why are you multiplying it with 50000? Is workers a separate variable that's globally defined and not shown? Communication is an important skill in this field, and comments are often helpful tools to document your code for others to understand.
I think an alternative answer could be formatted in this way:
let i = 0;
function increment(){
i++;
document.querySelector('h3').textContent = i
}
document.querySelector('button').addEventListener('click',increment)
<button>Click Me</button>
<h3>0</h3>

Every time user clicks on the button I need the next value from the array in Javascript

I'm currently trying to loop an array in a function. This function supposed to be used for a button, which gives every time a different value from the array when its pressed.
var list=['DEFAULT','ADVANCED','DEVELOPMENT'];
Every time user clicks on the button i need the next value from the array. (when its "DEVELOPMENT", next should be "DEFAULT"). Is it possible to do it without using a global variable ?
If you fine with changing array chiliNUT's answer would work (shift/push to implement circular buffer).
Alternatively you can keep current selection and loop that with %. To avoid global variables wrap counter in a function to capture value.
Sample (assuming usage of JQuery, you can find equivalent addEventListener code yourself):
$(function()
{
// outside of click handler to be able to preserve values between clicks
var current = 0;
$("button.next").click(function()
{
alert(list[current]);
current = (current + 1) % list.length;
});
}
<button class="next">Next</button>
something like this. shift pulls off the first element. push sends it to the back.
var list=['DEFAULT','ADVANCED','DEVELOPMENT'];
function nextWord() {
var word=list.shift();
list.push(word);
console.log(word);
return word;
}
nextWord();//DEFAULT
nextWord();//ADVANCED
nextWord();//DEVELOPMENT
nextWord();//DEFAULT
nextWord();//ADVANCED
nextWord();//DEVELOPMENT
//...
<button onclick=nextWord()>Next Word</button>

Javascript Function arguments as variables

Firstly i would like to note this is my first time using this site so if I do something incorrectly, i am sorry. Secondly i am intermediate at JavaScript but have only been truly been coding with for 3 days and am using it in an incremental game (more for myself to learn than others as there are quite a few out there). I've been doing pretty good and learning more as i go.
My problem is that I've gotten stuck using a function with arguments, my code looks like this:
<button onClick="getStorg(gargAmm,'gargAmm')"> Get Garage </button>Ammount: <span id="gargAmm">0<br />
Which is the HTML that launces the Function:
var gargAmm = 0;
function getStorg(buildAmm,buildID)
{
buildAmm = buildAmm + 1;
document.getElementById(buildID).innerHTML = buildAmm;
}
The display will make the "Amount:" go up to one when the button is first clicked, but then stalls. I've tried rearranging all sorts of variables and such but i just don't know why this doesn't work. Can anyone help?
What you're doing is you're using the Global variable value
var gargAmm = 0;
Whenever you call the function it uses the same value as zero and increments it.
So your getting the value as 1 and its not incrementing further.
I have tried an another approach to solve your issue have a look at it.
<button onClick="getStorg('gargAmm')">
Get Garage
</button>Ammount: <span id="gargAmm">0</span><br />
Here is the javascript
function getStorg(buildID)
{
var d= document.getElementById(buildID);
var t= parseInt(d.innerText);
t=t+1;
document.getElementById(buildID).innerHTML = t;
}
Here the text from the span is taken and converted to int and then incremented the value
and inserted back into span.
Here is the Working fiddle http://jsfiddle.net/p8E4G/
Simple:
function myFunc(a,b) {
b = b || 0;
// b will be set either to b or to 0.
}

JavaScript Incrementing a number in an array

I want to increment a value in a array when a link is pressed in JavaScript
i Used the following code
<script type="text/javascript">
var i=0;
var numbers = new Array();
function go(val){
numbers[i]=val;
i++;
alert(numbers[i]);
}
</script>
Called the Function like this
<a href='javascript:go(1)' </a>
but always the alert prompts me 'undefined'
The alert is correct -- before you do your alert, you incremented i. You're looking at the next element after the one you just entered.
After calling the method once, your array looks like this:
numbers[0] = 1;
numbers[1] = undefined;
and i == 1.
After calling it again, the array looks like:
numbers[0] = 1;
numbers[1] = 1;
numbers[2] = undefined;
and i == 2.
Hopefully you can see that this method will always alert undefined
That's because you increment "i"
i++;
right before you put up the alert! Thus "i" will alwuays refer to the next array slot to use, not the one you just populated.
You could change the alert to use "i-1"
alert(numbers[i - 1]);
You are setting numbers[0] = 1 and then incrementing i which becomes 1 so alert(numbers[1]) is undefined, because it is undefined.
Do the alert before you increment. Also, use onclick or even better unobtrusively attach the event handlers in JS, not in the HTML.
Yes, it does that because you:
Create a completely empty array, and a pointer at 0.
When the function is called, you set the current pointer value to whatever was passed in...
...and then increment the pointer, so it's now pointing past the end of all the elements.
Now you look at the element in the array that's being pointed at, which has to be undefined because of the way you're managing the i pointer.
What were you hoping for this to do, by the way?
The question doesn't even match the code... or the code doesn't match the question?
"I want to increment a value in a array"
Your code is not incrementing the value, it's incrementing the index!
function go(val){
numbers[i]=val;
i++;
}
(where i is the index of the next undefined array element) is just the same as
numbers.push(val);
and if you need i to equal what will be the index of the next undefined array element then
i = numbers.length;
To increment the value you would have to first have numeric values for some array elements; then your function would need the index of which value to increment
var numbers = [0,0,0,0];
function go(i){
numbers[i]++;
}
// testing
go(1);
go(3);
go(1);
alert(numbers);
will show 0,2,0,1
But if your entire goal is to put a value into a new element on the end of an array then just use .push()
and .length will tell you how many elements there are; there is no need to increment an i

Categories

Resources