Write jQuery code to count the clicks of a button
Description: Show the number of clicks of the “Count” button. A second button must set the count back to 0.
Hint:
- Keep the count in a variable and update the text in each click.
HTML of the page
<button id="count">Count</button>
<button id="reset">Reset</button>
<p>Clicks: <span id="n">0</span></p>
Solution
var clicks = 0;
$('#count').on('click', function () {
clicks++;
$('#n').text(clicks);
});
$('#reset').on('click', function () {
clicks = 0;
$('#n').text(clicks);
});
$('#count').click().click().click();
console.log('after 3 clicks: ' + $('#n').text());
$('#reset').click();
console.log('after reset: ' + $('#n').text());
Console output
after 3 clicks: 3
after reset: 0
How it works
- The variable keeps the state outside of the handlers, so both handlers can use it.
Read jQuery Events.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |