Becasue we are now using modules in JS script. The scoping of the module is much different to the way we have previously interacted with the HTML page and inserting a JS script.
This has some disadvantages:
It requires some more code to add items like buttons and create new elements on the page
We cant use innerHTML anymore to inject code into divs which was quite fast and easy
Makes it harder to find bugs
Advantages:
Reduces the chances of our code having injection added
Better security of our application overall as the code is hidden in the source
The old way - We use to just append all the HTML and JS together. Using modules the onclick funtion will not work
const jobLists = document.getElementById('jobLists');
function printLists(add){
var text="";
data.forEach(element =>{
text+= `<div class="jobItem" onclick="addCompleted(${element.id})">${element.job}</div>`;
});
jobLists.innerHTMl = text;
}
The new way - create a div for each item and add an event listener to the div to update the status and append to child
const jobLists = document.getElementById('jobLists');
function printLists(data) {
data.forEach(element => {
const jobDiv = document.createElement('div');
jobDiv.className = element.completed === 'false' ? 'jobItem' : 'jobItemCompleted';
jobDiv.textContent = `${element.job} - ${element.completed}`;
//delete button
const delBut = document.createElement('button');
delBut.textContent = 'X';
delBut.addEventListener('click', () => { removeJob(element.id) });
if (element.completed === 'true') {
jobDiv.append(delBut);
}
// Add event listener for clicks to the div
if (element.completed === 'false') {
jobDiv.addEventListener('click', () => addCompleted(element.id));
} else {
jobDiv.addEventListener('click', () => jobItemCompleted(element.id));
}
jobLists.appendChild(jobDiv);
});
}