JavaScript Modules

Demonstration

Explanation

This provides a demonstration of creating a DOM element variable and adding an event handler to it in a module. The variable is exported from the module and imported into main.js

Note that the event handler code itself does not need to be imported into main.js, but the variable does have to be.

The relevant code from this file (the "My Button" HTML) and all the code from ./main.js and ./modules/my-module.js are shown below


code-examples/js-modules/index.php (this file)

<button id='my-btn'>My Button</button>
<script type='module' src='./main.js'></script>

code-examples/js-modules/main.js

import { myBtn } from "./modules/my-module.js";

code-examples/js-modules/modules/my-module.js

const myBtn = document.querySelector("#my-btn");
myBtn.addEventListener("click", function(){
  alert("Hallo from My Button");
});
export { myBtn };