0

I'm trying to improve the following code (for a button counter), but I'm unsure on initial inspection.

document.querySelectorAll("#minus")[0].addEventListener("click", function(e){
  e.stopPropagation();
  document.querySelectorAll("#number")[0].innerText = Number(document.querySelectorAll("#number")[0].innerText) - 1
})

document.querySelectorAll("#plus")[0].addEventListener("click", function(e) {
  e.stopPropagation();
  document.querySelectorAll("#number")[0].innerText = Number(document.querySelectorAll("#number")[0].innerText) + 1
})

How would I make this code more efficient?

I'm also looking to add a rule where the counter cannot reach zero.

Thankyou kindly for any help :)

2
  • A good way to remember the difference between Java and Javascript is that Javascript has "script" at the end. Commented Mar 14, 2020 at 14:19
  • While this code could be improved, it won’t show any performance issues. Commented Mar 14, 2020 at 15:09

1 Answer 1

1

You could shorten it by using querySelector, and add a condition like below:

var num = document.querySelector("#number")
, plus = document.querySelector("#plus")
, minus = document.querySelector("#minus")

minus.addEventListener("click", function(e){
  var value = Number(num.innerText)
  num.innerText = value === 1 ? 1 : value - 1
})

plus.addEventListener("click", function(e) { 
  num.innerText = Number(num.innerText) + 1
})
div{ text-align: center; cursor: pointer; width: 100px; outline: 1px solid blue; }
<div id="plus">+</div>
<div id="minus">-</div>
<div id="number">1</div>

Sign up to request clarification or add additional context in comments.

1 Comment

Thankyou Anurag - extremely helpful. How do I stop it reaching 0? Currently, it will allow to go to 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.