Search notes:

DOM example: onclick

HTML attribute

This example assigns a function-reference to the HTML attribute onclick:
<!DOCTYPE html>
<html>
<head>
  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <title>onclick</title>

  <script type="text/javascript">
    function clicked(elem) {
      alert(elem + " was clicked");
    }
  </script>
</head>
<body>

  <form action="#">
    <input type="button" value="Click me!" onclick="clicked(this);">
  </form>

  <div style="background-color:yellow; width: 100px; height: 100px" onclick="clicked(this);">
    Click me, too.
  </div>

</body>
</html>
Github repository about-Document-Object-Model, path: /Events/onclick/html-attribute.html

Dynamic button

The following example dynamically creates a button with a on click function attached to it.
<html><head>
<script>

function main() {
  var button = document.createElement('button');

  button.textContent = 'Click ME!';

  button.onclick = function () {
      alert(this);
  };

  document.body.appendChild(button);
}

</script>
</head>
<body onload='main()'></body>
</html>
Github repository about-Document-Object-Model, path: /Events/onclick/dynamic-button.html

See also

DOM examples
HTML element: input

Index