Search code examples
javascripthtmlreturnnan

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>

Solution

  • 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>