Issue
I made this simple counter app, code for html and js is below. The decrease button works fine, takes the h1 text down by 1 with each click. The reset button goes back to 0. But when I click the increase button, the text content changes from 0 to 01, then 011, then 0111, and so on. I can not figure out what the heck the problem is. I just want it to increase by 1!!
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Counter</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1>Counter</h1>
<h1 id="counter">0</h1>
<button class="btn btn-danger" id="dec">Decrease</button>
<button class="btn btn-warning" id="res">Reset</button>
<button class="btn btn-success" id="inc">Increase</button>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL"
crossorigin="anonymous"></script>
<script src="index.js"></script>
</body>
</html>
const decButton = document.querySelector('#dec')
const resButton = document.querySelector('#res')
const incButton = document.querySelector('#inc')
const counter = document.querySelector('#counter')
resButton.addEventListener('click', () => {
counter.textContent = 0;
})
decButton.addEventListener('click', () => {
counter.textContent -= 1;
})
incButton.addEventListener('click', () => {
counter.textContent += 1;
})
I tried changing from arrow functions to traditional functions, I tried changing .textContent
to .innerText
, I'm at a loss.
Solution
In your script Javascript may recognize the textcontent as a string type instead of an actual int so it actually does concatenate a string rather than adding +1 to an actual int, you can try to use ParseInt in order to convert it to an actual number, after that if you want of course, you can easily convert the number to a string again.
Anyway in your code instead of
incButton.addEventListener('click', () => {
counter.textContent += 1;
})
you should go with something like:
decButton.addEventListener('click', () => {
counter.textContent = parseInt(counter.textContent) + 1;
})
Answered By - Scarlet D.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.