Web Platform Javascript

Starter Script

Here is a starter script. It will print "Document ready" when it loads, and if you have a button with id "activateButton", it will print "Clicked" when you click it. For more information on how this little snippet works, please read the reset of the documentation here.

Make sure you link your script with the SCRIPT tag.

HTML (eg 'index.html'):

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="style.css">
  <title>skeleton</title>
</head>
<body>
  <button id="myButton">Button</button>
  <script src="script.js"></script>
</body>
</html>

Put your event wiring-up in the document ready handler, and make separate named functions for each handler.

Javascript (eg 'script.js'):

console.log('Script running');

// Page is loaded! Now event can be wired-up
const onDocumentReady = () => {
  console.log('Document ready');

  // Wire-up click event
  document.getElementById('myButton').addEventListener('click', onButtonClicked);
}

// Called according to 'click' event
const onButtonClicked = (e) => {
  console.log('onButtonClicked.');
  console.dir(e);
}

// Call onDocumentReady when loaded
if (document.readyState != 'loading') onDocumentReady();
else document.addEventListener('DOMContentLoaded', onDocumentReady);

For a larger example see the web starter

See a live demo