Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

83
Views
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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!