document.addEventListener("DOMContentLoaded", function() {
// Scenario 1
const btn = document.querySelector(".test");
btn.addEventListener("click", () => {
const fragment = document.createDocumentFragment();
var x = document.createElement('p');
x.className = "di";
x.style.background = "aqua";
for (var i = 1; i < 5; i++) {
x.textContent = ' Change background color for ' + `${i}` + " element";
x.id = 'para' + `${i}`;
fragment.append(x.cloneNode(true));
}
document.body.append(fragment);
//Nested addeventlistener
document.getElementById("para1").addEventListener("click", () => {
para1.style.background = "yellow"
});
document.getElementById("para2").addEventListener("click", () => {
para2.style.background = "yellow"
});
function changeBackgroundColor(elem) {
elem.style.background = "yellow";
}
//Nested addeventlistener
document.getElementById("para3").addEventListener("click", changeBackgroundColor(para3));
document.getElementById("para4").addEventListener("click", changeBackgroundColor(para4));
});
});
<button class="test">create 4 elements</button>
Step 1: Click on the HTML Button 'create 4 elements' to create 4 <p>
elements.
Observation 1: for the 1st and 2nd <p>
elements which have arrow function inside their addeventlisteners , the individual <p>
elements need to be explicitly clicked individually to change their background color from aqua to yellow.
Observation 2: for the 3rd and 4th <p>
velements which dont have arrow function inside their addeventlistener ,the background color has defaulted to yellow without clicking on the 3rd or 4th <p>
elements
So does this mean the click event in Observation 2 has no effect ? Also note there are nested AddEventListeners