0

Say I have a website with a file structure like this:

index.html
main.js
modules/my-module.js

index.html contains (along with a lot of HTML):

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

main.js contains:

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

and modules/my-module.js contains:

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

Now if I click on the button I get an alert as expected.

The problem I am having is that I have some information (ie variables with values such as strings, arrays etc) in other script tags on the index.html page which I need in modules/my-module.js

I do not want to use a global variable for this

I thought of creating an element(s) on the index.html page with data set attributes as keys and assign values to them. The element could then be accessed from modules/my-module.js and its data set attributes would be readable. This does work when I try it but it seems a long winded way of getting access to information available on the index.html page.

Is there any other approach which would be more direct?

I would prefer an answer to the question rather than being told I am an idiot or marking the page as a duplicate and pointing to a page that is not a duplicate. Just because I mention the word global does not mean this is a question about how to create a global to the kind editor who directed me to a page on how to make a global.

user3425506
  • 1,285
  • 1
  • 16
  • 26
  • 2
    Sounds like you better off create a class or a function returned by the module, where you can pass your data into it. Or use event listeners/messenger/observers to communicate between scripts/modules. – vanowm Mar 30 '22 at 23:17
  • one reason I do not want to do that is because I am trying to organise my code by using modules so that code relating to the same thing is in the same module. If I have to export code out of the module and pass arguments into it then my code base seems to become less well compartmentalised. I end up with a lot of somewhat random stuff in main.js or back in the index.html – user3425506 Mar 31 '22 at 06:05
  • I wonder why my post was marked as a duplicate of 'how to make a global' when it only mentioned that in passing. Does someone get points for marking something as a duplicate? – user3425506 Mar 31 '22 at 06:08

0 Answers0