user3697129 user3697129 - 5 months ago 9
Javascript Question

JavaScript button event handler not working

I am learning javascipt and now i have a piece of code but i am unable to get this to work, javascript isn't executed. I have already searched the web but i can't find an answer. Maybe you guys can help me with this.

HTML

<html>
<head>
<title>Text Game</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<button><span id="click">0</span></button>
</body>
</html>


Javascript

// Variables
var waarde = {
amount:2
};

$(document).ready(function() {
updateValues();
});

function updateValues() {
document.getElementById("click").innerHTML = waarde.amount;
}

$('#click').click(function() {
waarde.amount = waarde.amount + 1;
updateValues();
});

Answer

You have a couple of issues here:

Issue #1:

The element does not exist in the DOM to bind to yet, so do any or all of the following:

  1. Move your script tag to the footer, right before the closing </body> tag (generally best practice anyway).
  2. Use event delegation to bind to events on future elements.
  3. Put all the JavaScript in the ready handler.

Issue #2:

You should not bind a click event handler on an element inside a button, it will not work in specification compliant browsers as the button consumes the event, and it not propagated to children.

See the HTML5 spec for button for reference:

Content model:

Phrasing content, but there must be no interactive content descendant.

Instead, bind the click event handler to the button itself.

// Variables
var waarde = {
  amount: 2
};

$(document).ready(function(){
  updateValues();
});

function updateValues(){
  document.getElementById("click").innerHTML = waarde.amount;
}

// Binding to the button element using event delegation.
$(document).on('#button').click(function(){
  waarde.amount = waarde.amount + 1;
  updateValues();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="button"><span id="click">0</span></button>

Also, unless you need the span element for something else, you could get rid of it and just use:

document.getElementById("button").innerHTML = waarde.amount;