Reputation: 49
How can I increase and decrease 12 by one each time I press + and -? One more questions is I have other buttons which need to have the same functionality. For those other buttons, do I need to add the same class name and will they work the same? I have been told that I can't have two id which is why I am avoiding using id. Can I achieve this using id? How can I go about that?
const countUp = document.querySelector('.countUp')
const countDown = document.querySelector('.countDown')
countUp.addEventListener('click', () => {
let count = 0
count = count + 1
const counter = document.querySelector('.num')
counter.innerHTML = count
})
countDown.addEventListener('click', () => {
count = count - 1
const counter = document.querySelector('.num')
counter.innerHTML = count
})
<div class="rating">
<button class="countUp">+</button>
<span class="num">12</span>
<button class="countDown">-</button>
</div>
Upvotes: 1
Views: 78
Reputation: 10765
Move your declaration of the variable count
out of the event listener(s) and give it a global scope, and set it to the value of the span on initialization with the parseInt
function.
const countUp = document.querySelector('.countUp');
const countDown = document.querySelector('.countDown');
const counter=document.querySelector('span.num');
let count = parseInt(document.querySelector('span.num').textContent);
countUp.addEventListener('click',() => {
count++;
counter.innerHTML = count;
});
countDown.addEventListener('click', () => {
count--;
counter.innerHTML = count;
});
<div class="rating">
<button class="countUp">+</button>
<span class="num">12</span>
<button class="countDown">-</button>
Upvotes: 2