-1

I have two button Pulse and Minus. when the plus get clicked I want the points to increment and when the minus get clicked I want the points to decrement. For some reason when I click both button the points get decremented. Can someone please help me with this problem?

const incAndDecPoints = function () {
  const playerOnePoints = document.querySelector(".points-pl-one");
  let value = playerOnePoints.innerHTML;
  playerOnePluseBtn === "click" ? value++ : value--;
  document.querySelector(".points-pl-one").innerHTML = value;
};

playerOnePluseBtn.addEventListener("click", incAndDecrePoints);
playerOneMinusBtn.addEventListener("click", incAndDecrePoints);
  • Use [event delegation](//developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_delegation) instead of assigning multiple event listeners — it’s more maintainable, and applies to dynamically added elements. E.g., use an [event argument](//developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#The_event_listener_callback)’s [`target`](//developer.mozilla.org/en-US/docs/Web/API/Event/target). See [the tag info](/tags/event-delegation/info) and [What is DOM Event delegation?](/q/1687296/4642212). – Sebastian Simon Jul 07 '21 at 00:26

1 Answers1

0

You could just make a universal function to add or subtract points, and call it with different parameters on both button clicks:

const addPoints = function(amount) {
  const playerOnePoints = document.querySelector(".points-pl-one");
  let value = +playerOnePoints.innerText;
  value += amount;
  document.querySelector(".points-pl-one").innerText = value;
};

playerOnePluseBtn.addEventListener("click", () => addPoints(1));
playerOneMinusBtn.addEventListener("click", () => addPoints(-1));
Hao Wu
  • 17,573
  • 6
  • 28
  • 60