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.