0

document.body.style.background = 'white';

function changeMood() {
  document.body.style.background === 'white' ?
    document.body.style.background = 'rgb(20, 20, 20)' :
    document.body.style.background = 'white';
}
<section class="mode" onclick="changeMood()">
  <i id="mood-icon" class="fas fa-adjust fa-2x">click</i>
</section>

Why do I have to double click so that the onclick changes happen?

Phil
  • 157,677
  • 23
  • 242
  • 245
Qatora
  • 11
  • 2
  • 2
    Your code works fine, no double click needed – CertainPerformance Nov 15 '21 at 02:34
  • I certainly wouldn't use a ternary statement in place of an `if` here; it might _work_ but it reads terribly – Phil Nov 15 '21 at 02:36
  • @Phil Nothing wrong with conditional operator if done properly IMO. `const { style } = document.body; style.background = style.background === 'white' ? 'rgb(20, 20, 20) : 'white'` but toggling a class would be more elegant – CertainPerformance Nov 15 '21 at 02:38
  • 1
    @CertainPerformance Using a ternary to assign a value based on alternating state . Using a ternary to execute different statements (IMO) – Phil Nov 15 '21 at 02:40
  • @SebastionSimon I don't see how either of those duplicates apply to this question – Phil Nov 15 '21 at 02:46
  • One of them is *probably* what's actually happening on OP's side, but there's no MCVE, maybe a miscopy or something. – CertainPerformance Nov 15 '21 at 02:47

0 Answers0