Search code examples
javascripthtmljqueryprop

Disable and Enable click event on div from button type


I'm building Simon colors game with jQuery and I'm trying to disable the click event while the game is off or the player clicked on the wrong color. I'd read on the internet about the .prop('disalbe', true) and about .attr('disabled', 'disabled') but rn both of them didn't work for me. I'm using divs and not buttons elements

  <div class="container" id="container">
    <div class="row">

      <div type="button" id="green" class="btn green">

      </div>

      <div type="button" id="red" class="btn red">

      </div>
    </div>

    <div class="row">

      <div type="button" id="yellow" class="btn yellow">

      </div>
      <div type="button" id="blue" class="btn blue">

      </div>

    </div>

  </div>
allButtons.click(function() { // CLICK EVENT LISTENER
  const userChosenColour = this.id;
  userClickedPattern.push(userChosenColour);
  const userButton = $(`#${this.id}`);

  userButton.fadeTo(100, 0.1, function() { $(this).fadeTo(500, 1.0); });
  makeSound(this.id)


  if (checkAnswer(userClickedPattern.length)) { // CONDITIONS TO CHECK THE CURRENT CLICK
    if (userClickedPattern.length === gamePattern.length) {
      title.text('Success')
      setTimeout(function() {nextSequence()}, 1000);
    }
    return true;
  } else {
    // allButtons.attr('disabled',true);
    title.text('Wrong');
    makeSound('wrong');
    flashBackground();
    allButtons.prop('disabled', true);
    setTimeout(function() {resetGame()}, 500);
    return false;
  }
});

rn the result is nothing happen. thank you for your help here !


Solution

  • You can set the CSS property pointer-events to none to prevent clicks.

    allButtons.css('pointer-events', 'none'); // Disable clicks
    allButtons.css('pointer-events', ''); // Re-enable