0

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

Richard
  • 27
  • 9
  • 1
    What is `actionEventListener`? They're just called event listeners, and `addEventListener()` adds them. – Barmar Apr 10 '23 at 17:07
  • 1
    You're not passing a function reference, you're calling the function immediately. – Barmar Apr 10 '23 at 17:08
  • 1
    addEventListener expects a function as 2nd parameter. `changeBackgroundColor` is a function, but `changeBackgroundColor(param2)` is equal to the value returned by executing that piece of code (undefined). – James Apr 10 '23 at 17:08
  • @james so how to pass a param then? – Richard Apr 10 '23 at 17:52
  • 1
    Wrap it in an anon function, `element.addEventListener("click", () => changeBackgroundColor(para3))` – James Apr 10 '23 at 17:56

0 Answers0