2

I have this simple app where I'm tyring to trigger a function inside Javascript module by pressing a html button but it seems to do nothing. I looked at another thread about this same topic but does not seem to work for me. As soon as I take the type="module" off from the script tag it works so it propably has something to do with that. Console gives no errors so I have no idea what I'm doing wrong here.

index.html

<body>
    <button id="test">Click me!</button>
    <script type="module" src="/app.js"></script>
</body>

app.js

document.getElementById("test").addEventListener("click", () => {
    console.log("Hello!");
});
8
  • 2
    Is your script running before the elements have been rendered in the document? Try moving your script tag to the bottom of your body Commented Feb 20, 2018 at 17:39
  • 1
    try <button id="test" onclick="alert('ok');">Click me!</button> Commented Feb 20, 2018 at 17:40
  • 2
    The html document is processed from top down, and at the moment the script runs there is no such thing as document.getElementById("test"), and you will see an error message to that effect in the browser console. Commented Feb 20, 2018 at 17:40
  • 2
    type='module' - I don't think that code is suitable for an ES6 module. Try without type param or type='text/javascript' Commented Feb 20, 2018 at 17:45
  • 1
    stackoverflow.com/questions/37624819/… - I did close this question, but I'm not satisfied the "duplicate" is a duplicate, but you do need to make some changes to your browser settings as James says to get this to work. I've made the change in FF and tested your code and it works fine. @iWillBeMaster. Let me know if that works and I'll close this as the duplicate. Commented Feb 20, 2018 at 18:03

1 Answer 1

3

It seems that 2 things are missing:

The import statement on your html document and the export statement on your snippet to allow there to be a module and can to be imported.

export function yourModule() { 
  // ...
 }

<script type="module"> import {yourModule} from './app.js';
 </script>

Look this: https://jakearchibald.com/2017/es-modules-in-browsers/

Also, check if your browser already support the module type.

Sign up to request clarification or add additional context in comments.

2 Comments

It seems to work on chrome but not on firefox. Apparently i have to do a change to the setting in FF to get it to work.
Firefox 54 – behind the dom.moduleScripts.enabled setting in about:config

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.