I’m trying to import a function from js file to HTML file but cannot make it work. When I paste the function to HTML file directly it works just perfect but I would like to keep them separately so I assume I must be doing something wrong with the import. Could anyone please check what I’m doing wrong?
The js function (I included only the beginning as there is a lot of links and it may be confusing to look at):
// toggle main img
let myVar2 = setInterval(changeImg, 2000);
let myImage = document.getElementById("main_img");
export function changeImg() {
let mySrc = myImage.getAttribute('src');
switch (mySrc) {
case "./assets/images/severin-candrian-unsplash.jpg":
myImage.setAttribute('src', "./assets/images/header_img2-unsplash.jpg");
break;
// rest of code
}
}
Have you checked the browser console for errors? I’d first log something at the top of the script file:
console.log('TEST')
If you can’t see that in the console, the path is wrong.
If you see the log, but your script doesn’t do anything, it’s possible that you’re trying to manipulate elements that aren’t in the DOM yet. In that case, you can put your code inside a DOMContentLoaded callback:
Maybe I’m missing something but do you only have one js file? If so the function export isn’t doing anything. You would have to import it in another js file and it would only work with modules type="module" on the script element.
Are you not getting a SyntaxError: Unexpected token 'export' in the console?
Changing the type value worked! At the moment I have only one js file because I couldn’t make even one function work so I haven’t created more yet. It’s my first “real” project so I am a bit lost with the structure. Thank you so much!
If you only need one js file you have no need for modules (import/export). Pretty sure if you did need modules you would know. Modules are mainly useful in larger applications. Just remove the export and you won’t need the script to be of type module.
You can check out the MDN guide on modules to learn more.