I need help with a JavaScript function that creates random numbers between 1 and 10 when I click a button. The tricky part is that each new click should add the new random number to the previous total, making it grow bigger each time.
Here’s what I have so far, but I can’t figure out how to keep adding the numbers together:
I want the numbers to keep adding up so if I get 3 on the first click and 7 on the second click, the total should be 10. How can I modify this code to store and add the values?
Your code generates a fresh random number each click but doesn’t keep track of anything. You need a variable that sticks around between clicks. Move your sum variable outside the jQuery ready function - or at least outside the click handler. Try var runningTotal = 0; right after your document ready line. Then in your click function, do runningTotal += randomResult; and log it with console.log('Running total: ' + runningTotal);. I’ve done this tons of times for game scores. It’s all about variable scope - stuff declared inside the click function resets every time, but outer scope variables stick around between clicks.
This is a common issue when managing state in JavaScript. To keep a running total that persists across button clicks, you need to declare a variable outside the click handler. Start by placing var accumulatedTotal = 0; right after your document ready function. Then, within your click handler, simply add to this variable using accumulatedTotal += randomResult; after generating each random number. If you want to display the current total on the page, you could update an element like $('#total-display').text('Total: ' + accumulatedTotal);. Maintaining this variable in the outer scope prevents it from resetting with each click, which is crucial for accumulating values.
just declare a variable outside ur click func to track the total. put var totalSum = 0; before the click event, then add totalSum += randomResult; inside after u get the random number. display it whenever u want.