Search code examples
javascripthtmlvariablesinnerhtmlgetelementbyid

Javascript write variable to div


I'm trying to write the variable "current" to the div "bank" using the following code when the user clicks on the image: document.getElementById('bank').innerHTML = current

According to my research, this should work, but it doesn't. Here's my code:

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <link rel="stylesheet" type="text/css" href="css/default.css">
        <script>
            var current = 0;
            var totalThisGame = 0;

            function onButtonClick
            {
                current = current +1;
                totalThisGame = totalThisGame +1;
                document.getElementById('bank').innerHTML = current;
            }
        </script>
    </head>
    <body>
        <div id="left">
            <div id="bank">
            </div>
            <img id="image" src="img/image.png" alt="image" onclick=onButtonClick();>
        </div>
        <div id="middle">
        </div>
        <div id="right">
        </div>
    </body>
</html>

Solution

  • you miss the () behind your function

    function onButtonClick()
                {
                    current = current +1;
                    totalThisGame = totalThisGame +1;
                    document.getElementById('bank').innerHTML = current;
                }
    

    your code is working fine for me