2

What I want my function to achieve for my javascript function is for every second to either randomly subtract or add (a random number) to a number held in a div.

Here's what I have so far.

It doesn't work, it seems to append the number to the end of the div value (100), and also it doesn't take into account that I want it to either randomly add or subtract (it just adds at the moment)

    setInterval(function(){
        random = (Math.floor((Math.random()*15)+1)); 
        currentnumber = document.getElementById('number');

        document.getElementById('number').innerHTML =  currentnumber + random;

     }, 1000);
J. Podolski
  • 201
  • 6
  • 16
  • `currentnumber` should probably be `.innerHTML` and not the element itself. – bozdoz Jan 21 '14 at 23:46
  • Maybe you could try currentnumber = parseInt(document.getElementById('number').innerHTML); ? (edit: yes innerHTML is what you're after, otherwise you're manipulating the DOM object) – Dan H Jan 21 '14 at 23:46
  • 1
    For the record, this question was a clear oversight of missing `innerHTML` when declaring the variable. – bozdoz Jan 22 '14 at 04:14

4 Answers4

7

parse the current value as an integer, and then do another math.random and use it to decide negative or positive. Lastly, you need to use the innerHTML of currentnumber, not the entire node. So something like this should work:

setInterval(function(){
    random = (Math.floor((Math.random()*15)+1));
    var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
    random = random * plusOrMinus; 
    currentnumber = document.getElementById('number');

    document.getElementById('number').innerHTML =  parseInt(currentnumber.innerHTML) + random;

 }, 1000);

WORKING FIDDLE

Rooster
  • 9,954
  • 8
  • 44
  • 71
1

.innerHTML returns you a string which you'll need to parse into an integer to perform the addition or subtraction. Have a look at a number of methods listed in the following SO question

How do I convert a string into an integer in JavaScript?

Community
  • 1
  • 1
Ani
  • 1,655
  • 3
  • 23
  • 37
1

currentnumber is a DOM object, and you can't add that to a number.

var div = document.getElementById('number');
div.innerHTML = Number(div.innerHTML) + 3;

Notice you are getting the innerHTML of the div, converting that to a Number(), adding your random number to it, and THEN setting your div.innerHTML to your new value.

http://jsfiddle.net/9LqQG/1/

photodow
  • 255
  • 2
  • 8
0

Maybe try something like this:

setInterval(function(){
    random = (Math.floor((Math.random()*15)+1)); 
    currentnumber = parseInt(document.getElementById('number').innerHTML);

    document.getElementById('number').innerHTML =  currentnumber + random;
 }, 1000);

Your currentnumber variable needs to get the innerHTML of the element, then parse the string into an integer.

jsFiddle

Blundering Philosopher
  • 6,245
  • 2
  • 43
  • 59