KikePeris KikePeris - 1 month ago 7
HTML Question

my addEventListener is not working

I'm trying to do something very simple, when I click on my apple image I should get a text displayed right on the side of my character image (Anthony) and a number inside my appleNumber div. I used addEventListener but something seems wrong (I'm on Chrome). The code:

<script>
var appleButton = document.getElementById("apple");
appleButton.addEventListener("click", showAnthonyText);
appleButton.addEventListener("click", showNumber);

function showAnthonyText() {
document.getElementById("anthonyDelishBubble").style.display='block';
}
function showNumber() {
document.getElementById("appleNumber").innerHTML = "1";
}
</script>

<body>

<div id="anthonyGameTitle">Feed Amicable Anthony Some Apples</div>
<div id="anthonyGameMainContainer">
<div id="anthonyAppleGame"><img src="AmicableAnthony.png" alt="AmicableAnthony" height="300" width="300"></div>
<div id="apple"><img src="apple.png" alt="apple" height="80" width="80"></div>
<div id="anthonyDelishBubble"><img src="delish.png" alt="delish" height="80" width="80"></div>
<div id="appleNumber"></div>


</div>
</body>

Answer

Your code is executed when your html wasnt loaded yet. Run your code in a function launched when your body is loaded for instance :

<script>
function init() {
    var appleButton = document.getElementById("apple");
    appleButton.addEventListener("click", showAnthonyText);
    appleButton.addEventListener("click", showNumber);
}

function showAnthonyText() {
    document.getElementById("anthonyDelishBubble").style.display = 'block';
}

function showNumber() {
    document.getElementById("appleNumber").innerHTML = "1";
}
</script>

<body onload="init()">
.....
</body>

or add your initialization after your html :

<body>

    <!-- your html body here -->

    <script>
    var appleButton = document.getElementById("apple");
    appleButton.addEventListener("click", showAnthonyText);
    appleButton.addEventListener("click", showNumber);

    function showAnthonyText() {
        document.getElementById("anthonyDelishBubble").style.display = 'block';
    }

    function showNumber() {
        document.getElementById("appleNumber").innerHTML = "1";
    }
    </script>
</body>