Home How to decrement a counter if a button is clicked the second time

# How to decrement a counter if a button is clicked the second time

user8941
1#
user8941 Published in September 20, 2018, 4:34 pm

I have the following code,each time a button is clicked it adds it to a counter as shown bellow, what i am trying to achieve is that if the same button is clicked the second time it must decrement the counter, currently if i press a single button multiple times it adds to a counter,i only want it to add to a counter when its clicked on the first time,the second time its clicked it must decrement the counter,i am trying to click each button only once and if its clicked on the second time it must decrement the counter

var counter = 0;

function count() {
$('#notify').addClass("notification");$("#notify").html(counter);
}

\$('body').on('click', '.btn', function(e) {
counter++;
count();
});
position: absolute;
display: block;
text-align: center;
font-size: 9px;
font-weight: 700;
letter-spacing: -1px;
width: auto;
min-width: 8px;
height: 9px;
line-height: 4px;
color: #fff;
border: 2px solid #fff;
background-color: #b60000;
}
<div class="marketoptionslist">
<a><button class="btn" >
click me
</button></a>
<a><button class="btn">
click me
</button ></a>
<a><button class="btn">
click me
</button></a>
<a><button class="btn">
click me
</button></a>
</div>

and suggestions?

• Are you trying to build a toggle system? Ie. the third click should add one, and the fourth click should subtract – Rory McCrossan Feb 14 at 10:00
• It sounds like the counter will always toggle between 0 and 1 when you click. Have you thought about how you could achieve that within your .on('click',... handler? – Steve Greatrex Feb 14 at 10:01
• use simply a flag and declare it as false and in in button click check if its fals e or true if false then it will be first click and then do your logic and change it as true and in the coming hits you can check the same logic if it is true then go for decrement logic – Arunprasanth K V Feb 14 at 10:01