'Click Instantly Triggers Event Listener That Is Created By The Click
I have a button with an event listener. When somebody clicks it, all content on my webpage gets replaced with something else, and a new event listener is put on the whole body of the page. However, clicking the button instantly triggers the new event listener that is only created after clicking it. Of course clicking the button also means that you clicked the body, but the new event listener is only created through the click, so I thought it wouldn't instantly trigger. I don't understand why that's happening or how to prevent it. I hope my question isn't too stupid. I'm pretty new to this whole thing and trying to teach myself the basics.
$("button").on("click", () => {
$("body").on("click", () => {
$("body").css({"background-color": "red"});
});
$("body").css({"background-color": "green"});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click Me</button>
Edited to make my point clearer. Edited again to include example. Why is the body turning red instead of green?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
