Dynamically added event handler disables the previous one in JavaScript

19 views Asked by At

I am creating buttons dynamically in JavaScript. Also adding dynamically an eventhandler to each button. For the last button it works but the previous ones simply are not working any longer. Here's my small piece of code. What do I do wrong?

<html>

<head>
    <script>
    var id = 0;

    function makeFunc(arg) {
        return function() {
            alert('selected ' + arg)
        }
    };

    function addElement() {
        document.getElementById('p1').innerHTML +=
            '<button id=\'id' + id + '\'>Button' + id + '</button>';
        document.getElementById('id' + id).onclick = makeFunc(id);
        id++;
    }
    </script>
</head>

<body>
    <button onclick="addElement();">Add Button</button>
    <p id="p1"></p>
</body>

</html>

it's also here: http://jsfiddle.net/q52a7fw0/

1

There are 1 answers

0
AmmarCSE On BEST ANSWER

When you use innerHTML like

 document.getElementById('p1').innerHTML +=
            '<button id=\'id' + id + '\'>Button' + id + '</button>';

you overwrite exisiting event handlers.

Instead, you should create the element and append it

function addElement() {
  var button = document.createElement('BUTTON');
  button.id = id;
  button.textContent = 'Button ' + id;
  button.onclick = makeFunc(id);
  document.getElementById('p1').appendChild(button);

  id++;
}

var id = 0;

function makeFunc(arg) {
  return function() {
    alert('selected ' + arg)
  }
};

function addElement() {
  var button = document.createElement('BUTTON');
  button.id = id;
  button.textContent = 'Button ' + id;
  button.onclick = makeFunc(id);
  document.getElementById('p1').appendChild(button);

  id++;
}
<body>
  <button onclick="addElement();">Add Button</button>
  <p id="p1"></p>
</body>