Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
});
like image 449
Stixs Avatar asked Jun 30 '26 08:06

Stixs


2 Answers

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;
like image 158
Alexander O'Mara Avatar answered Jul 01 '26 20:07

Alexander O'Mara


You should put this code:

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

Inside of $(document).ready(function(){}) function. $('#click') isn't in the DOM yet..

like image 25
aprok Avatar answered Jul 01 '26 20:07

aprok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!