I've the items.js
file that add the items in the page, the navigation.js
that detect the click on the items and the main.js
that load both files.
The problem is that since the items are loaded dynamic, the navigation.js
must be loaded after the items.js
.
I've solved this by adding a setTimeout
to the navigation.js
import.
My doubt is: there's a better way to do that without the setTimeout
?
main.js
import items from './_items.js';
import navigation from './_navigation.js';
items();
setTimeout(() => {
navigation();
}, 1000);
items.js
export default function () {
fetch('files/items.json').then(function(response) {
return response.json();
}).then(function(data) {
let body = '';
data.map(function(item) {
body += `<a href="#" class="link">${item.name}</a>`;
});
let div = document.getElementById('items');
div.innerHTML = body;
});
}
navigation.js
export default function () {
const links = document.querySelectorAll('.link');
links.forEach(el => el.addEventListener('click', event => {
event.preventDefault();
console.log('Click!');
}));
}