2

This has been asked many times before BUT in different cases so I don't really understand the previous answers. This is my code:

function enableEdit() {
  var btn = this.event.target;
  if (btn.innerHTML == "Edit") {
    document.getElementById("output").innerHTML = "You clicked the Edit button. Changing to Update";
    window.addEventListener("click", function () { disableEdit(btn); } );
    btn.innerHTML = "Update";
  }
  else if (btn.innerHTML == "Update") {
    document.getElementById("output").innerHTML = "You clicked the Update button. Changing to Edit";
    btn.innerHTML = "Edit";
    window.removeEventListener("click", disableEdit);
  }
}

function disableEdit(btn) {
    if (this.event.target != btn) {
        if (btn.innerHTML == "Update") {
            document.getElementById("output").innerHTML = "You clicked somewhere else. Reverting to Edit";
            btn.innerHTML = "Edit";
            window.removeEventListener("click", disableEdit);
        }
    }
}
<html>
  <body>
    <h1 id="output">Output</h1>
    <button type="button" onclick="enableEdit()">Edit</button>
  </body>
</html>

This works perfectly BUT I still don't understand this part:

window.addEventListener("click", function () { disableEdit(btn); } );
btn.innerHTML = "Update";

Why does the addEventListener trigger the function immediately? At first I put the btn.innerHTML = "Update" before the window.addEventListener but because the listener fires immediately and reads the button as "Update", I put that line below the addEventListener.

Can somebody explain to me in plain English this behavior which I find weird? Yes, I have read many tutorials but I have become more confused instead.

klediooo
  • 630
  • 1
  • 7
  • 25
astigmatik
  • 134
  • 1
  • 8
  • better to make a codepen / etc – digitalzoomstudio Sep 22 '20 at 07:04
  • 1
    you can pass parameters to an handler by using `.bind()` like this `window.addEventListener("click", disableEdit.bind(null, btn) );` – bill.gates Sep 22 '20 at 07:07
  • 1
    `window.addEventListener` in your code isn't triggered immediately, it is triggered when you're clicking on `window`. Notice, that `removeEventListener` can't remove a listener attached with an anonymous function. – Teemu Sep 22 '20 at 07:22
  • Just in case anyone else comes across this, I actually found that the better event to listen to is the mouseup. This is because a click event registers the mousedown AND mouseup. What happens when the event listener is added to the button, the first click on the button already has two events: mousedown then mouseup. Which is why the function is triggered when the mouseup occurs. More info here: [link]https://javascript.info/mouse-events-basics#:~:text=Events%20order&text=For%20instance%2C%20a%20left%2Dbutton,mousedown%20%E2%86%92%20mouseup%20%E2%86%92%20click%20.[/link] – astigmatik Oct 06 '20 at 03:39

0 Answers0