My goal is to create a JavaScript application that functions as a basic counting tool

I've encountered an issue with my simple counter code - it's not functioning properly. The goal is for the decrement function to stop running when the count reaches 0. I'd appreciate any help in troubleshooting what might be wrong.

let count = 0;

let displayCount = document.getElementById("count")

let incrementElement = document.getElementById("increment");
let decrementElement = document.getElementById("decrement");
let resetElement = document.getElementById("reset");

function increment() {
  let count = 0
  count++;
}

function decrement() {
  displayCount.textContent = count;
  if (count !== 0) {
    count--;
  }
}

function reset() {
  displayCount.textContent = count;
  count = 0;
}

displayCount = incrementElement.addEventListener("click", increment);
decrementElement.addEventListener("click", decrement);
resetElement.addEventListener("click", reset);

The code provided above was written by me, but unfortunately, when clicking the buttons, it seems to progress forward before functioning as intended. For instance, if the count is at 4 and the decrement button is clicked, it increments to 5 before going back down to 4, 3, 2, 1, 0.

Answer №1

let total = 0;

let displayTotal = document.getElementById("total")

let addElement = document.getElementById("add");
let subtractElement = document.getElementById("subtract");
let clearElement = document.getElementById("clear");

function add() {
  total++;
  displayTotal.textContent = total;
}

function subtract() {
  if (total > 0) {
      total--;
  }
  displayTotal.textContent = total;
}

function clear() {
  total = 0;
  displayTotal.textContent = total;
}

addElement.addEventListener("click", add);
subtractElement.addEventListener("click", subtract);
clearElement.addEventListener("click", clear);

I edited the let total = 0 inside add to avoid issues with closures, and removed the line

displayTotal = addElement.addEventListener("click", add);

as it was incorrect. Remember to update the textContent of the HTML element after performing the arithmetic operation. Everything else seems good, enjoy learning Javascript!

Answer №2

After creating a simple version, I realized that without your specific html code, I had to start from scratch.

<h1 id="count"></h1>
<button type="button" id="inc">Increment</button>
<button type="button" id="dec">Decrement</button>
<button type="button" id="reset">Reset</button>
<script src="script.js"></script> <!-- You will need to adjust the script tag according to your JavaScript file. If you are using inline JS code in your HTML file, remove the src attribute and place the code within the <script></script> tags -->
let count = document.querySelector("#count");
let incButton = document.querySelector("#inc");
let decButton = document.querySelector("#dec");
let resetButton = document.querySelector("#reset");
var num = 0;
count.innerText = num;

incButton.addEventListener("click", increment);
decButton.addEventListener("click", decrement);
resetButton.addEventListener("click", reset);

function increment() {
  num++;
  count.innerText = num;
}

function decrement() {
  if(num > 0) {
    num--;
  }
  count.innerText = num;
}

function reset() {
  num = 0;
  count.innerText = num;
}

Answer №3

Here is a solution that may help you out :)

<div>
        <div id="counter">0</div>
        <button id="increment">increment</button>
        <button id="decrement">decrement</button>
        <button id="reset">Reset</button>
    </div>
    <script type="text/javascript">
        var counter = 0;
        var displayCounter = document.getElementById("counter");

        var incrementButton = document.getElementById("increment");
        var decrementButton = document.getElementById("decrement");
        var resetButton = document.getElementById("reset");

        incrementButton.addEventListener('click',function () {
            if (counter < "1") {
                counter++;
                displayCounter.innerHTML = counter;
            } else {
                counter++;
                displayCounter.innerHTML = counter;
            }   
        });
        decrementButton.addEventListener('click',function () {
            if (counter != "0") {
                counter--;
                displayCounter.innerHTML = counter;
            }   
        });
        resetButton.addEventListener('click',function () {
            displayCounter.innerHTML = "0";   
        });
    </script>

Answer №4

        let counter = 0;

        let displayCounter = document.getElementById("counterDisplay")

        let incrementButton = document.getElementById("incrementBtn");
        let decrementButton = document.getElementById("decrementBtn");
        let resetButton = document.getElementById("resetBtn");

        function increaseCount() {
            counter++;
            displayCounter.innerText = counter;
        }
        function decreaseCount() {
            if (counter !== 0) {
                counter--;
            }
            displayCounter.innerText = counter;
        }
        function resetCount() {
            counter = 0;
            displayCounter.innerText = counter;
        }

        incrementButton.addEventListener("click", increaseCount);
        decrementButton.addEventListener("click", decreaseCount);
        resetButton.addEventListener("click", resetCount);

To display a variable, you must first define it and then update the HTML content accordingly. Additionally, setting the listener for the increment button as a separate variable is unnecessary and could lead to errors.

Answer №5

Below is a concise and testable illustration.

let num = 0

const numberElement = document.getElementById("number")
const addElement = document.getElementById("add")
const subtractElement = document.getElementById("subtract")
const resetElement = document.getElementById("reset")

function add() {
  num++
  numberElement.textContent = num
}

function subtract() {
  if (num > 0) num--
  numberElement.textContent = num
}

function clearNum() {
  num = 0
  numberElement.textContent = num
}

addElement.addEventListener("click", add)
subtractElement.addEventListener("click", subtract)
resetElement.addEventListener("click", clearNum)
<button id="subtract">-</button>
<span id="number">0</span>
<button id="add">+</button>
<br>
<button id="reset">reset</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a polling feature using a Grease Monkey script

I am looking for a way to run a Tamper Monkey script on a Facebook page that regularly checks a database for new data and performs certain actions. I have attempted to implement polling using AJAX, and below is the code I used: (function poll() { setT ...

Reveal a segment of a picture

Is there a way to display only a section of an image using either jQuery or another JavaScript method? For example: image: [ ] [ -------- ] [ - - ] [ - part - ] [ - - ] [ -------- ] [ ...

Architecting Angular for an efficient sorting directive

As a newcomer to Angular, I am exploring the best approach to accomplish a simple task. My goal is to update the order of a Project model in a database using the Angular $resource service. Here is my template structure: <table class="table table-hove ...

The process of registering with JWT tokens and the challenge that arises when a token expires

I had the idea to implement a registration process that requires users to provide their username, email (which must not already exist in the database), password, and confirm password. The project is built using NextJS with pages router and Typescript. impo ...

Best method to extract an item from an array using AngularJS

Just dipping my toes into AngularJS and pondering on a more streamlined approach: Currently, I have a factory that supplies me with an array of product objects. (For now, this data is hardcoded but will eventually be fetched from a RESTful API.) app.fact ...

Add a file to the input field using JavaScript and the input type="file"

I am facing the challenge of sending a file (up to a few MB) generated by JavaScript to a server using POST (not ajax POST). I am wondering how I can add a file to an input type="file" using JavaScript. After checking Pre-Populate HTML form file input, it ...

Looking for a way to identify when a DOM element is resized as a result of web fonts loading asynchronously?

Within this div element lies text styled with a custom font via CSS's @font-face attribute. The issue arises when the font hasn't loaded yet, causing a delay in updating the font style of the text within the div. As a result, taking measurements ...

Just starting out with Vue and hitting a roadblock with global variables

I am currently working on creating a filtered list in Native Vue, specifically compiling and running it for Android. export default { components: { card }, data: { search: 'An', level: "", }, computed: { searchI ...

The calculator is generating console logs, but there is no output appearing on the display

I'm currently working on a calculator project using JavaScript and jQuery. I am facing an issue where the numbers are not displaying on the screen when I press the buttons, but they do show up in the console log without any errors. I would appreciate ...

Broswer-based location retrieval APIs that do not rely on window.navigator to prompt users for their location

Is there an API available, other than those from Google, that can provide user location data for use with Mapbox GL and React? I'm already familiar with using window.navigator's getCurrentPosition method to access geolocation information. const ...

Converting PDO Fetch results into JSON using PHP

Trying to execute a MySQL query in a PHP file and return the results in JSON format to a Javascript function. PHP code: require_once("class.user.php"); $auth_user = new USER(); $stmt = $auth_user->runQuery(" SELECT * FROM projects; " ...

What could be causing me to receive an unpopulated string in react?

When attempting to pass a string ID to a function located in another file, I encounter an issue where the response from that function is consistently an empty string. Strangely enough, if I invoke the function again, the proper ID is displayed. The problem ...

Enhance Your Charts: Learn how to dynamically adjust zoom levels between two timestamps with just a simple form submission

I have a Zingchart Area Graph that displays events on a timeline with time on the X-Axis. I want to be able to automatically zoom into a specific timeframe on the graph based on user input from a form. For example, if a user selects a start time of 8 AM an ...

When the responsive navbar is activated, it obscures the body content, causing a block in

When attempting to create a solution, ensure that the responsive toolbar is enabled on your Chrome browser. My approach involves designing for mobile first and then adapting for desktop. However, I am encountering an issue where the hamburger menu opens an ...

Modifying the data of an HTML form using Javascript, encrypting the information, and transferring it to PHP

I am new to PHP and have a simple code management question. I would like to create an input box in HTML where someone can enter their name, and with the use of Javascript, generate a link with an encoded version of the name preceded by a website string. Wh ...

Improper ordering using insert method within a forEach loop

I have an array containing objects that I need to import into a sqlite3 database using a forEach loop. The process is working correctly, but I noticed that the objects are not being imported in the same order as they appear in the database. This is my app ...

Pattern matching for censoring various elements within a string

I'm utilizing regular expressions in JavaScript to redact certain information. The regex below successfully replaces part of the values. EDIT Original String: mysql --user=USER_NAME --host=DB_HOST --database=SCHEMA -p -e 'SELECT Expression: ...

Tips for maintaining the particles.js interaction while ensuring it stays under other elements

I have incorporated particle.js as a background element. By adjusting the z-index, I successfully positioned it in the background. While exploring solutions on the Github issues page, I came across a suggestion involving the z-index and this code snippet: ...

What are the methods for triggering multiple exceptions in NESTJS?

Can anyone provide some examples on how to structure the returns in this format? { "errors": { "due_date": [ "cannot be blank", "cannot be more than three years in the future", "cannot be ...

A code to ensure input values are always set to the maximum possible value

I recently developed a script that monitors the live value property of 3 <input> elements, correcting them if the live value is outside the specified range. However, I encountered an issue where the script automatically sets the value to the max as s ...