Show the text based on the current count of the counter

Currently, I have a simple Javascript counter function:

<body>
    <script type="text/javascript">
    var clicks = 0;
    function onClick() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks;
    };
    </script>
    <button type="button" onClick="onClick()">Add One To Chain</button>
    <p>Chain: <a id="clicks">0</a></p>

</body>

Now, I want to display different text messages to the user at various count points.

For example, when the counter hits 10, it should say hello. At 20, it could encourage the user to keep going, and at 30 - STOP! and so on.

I would appreciate any assistance with this task!

Answer №1

If you want to implement different actions based on the number of clicks, a switch statement can be useful:

switch (clicks) {
    case 10:
        message = 'Hello';
        break;
    case 20:
        message = 'Keep going';
        break;
    case 30:
        message = 'STOP';
        break;
    default:
        message = clicks;
        break;
}
document.getElementById("clicks").textContent = message;

Answer №2

This method takes a dynamic approach to alerting. It will display alerts based on the values provided in the prompts array.

var clicks = 0,
    prompts = ['Hey there', 'Almost finished', 'PAUSE'];

function handleClick()
{
    clicks += 1;

    var promptIndex = clicks / 10 - 1;

    if (clicks % 10 == 0 && prompts[promptIndex] !== undefined) {
        alert(prompts[promptIndex]);
    }

    document.getElementById("clicks").innerHTML = clicks;
};

Answer №3

To make this function properly, you can implement if-else statements in Javascript.

Below is a functional example:

var count = 0;

function incrementCount() {

  count += 1;

  if (count == 10) {
    alert("Hello");
  } else if (count == 20) {
    document.getElementById("count").style.color = "green";
    document.getElementById("count").innerHTML = count + " Keep Going";
  } else if (count == 30) {
    document.getElementById("count").style.color = "red";
    document.getElementById("count").innerHTML = count + " Stop!";
  } else {
    document.getElementById("count").innerHTML = count;
  }
}
<button type="button" onClick="incrementCount()">Increase Count by One</button>
<p>Count: <a id="count">0</a>
</p>

Answer №4

To simplify the process, follow this example with detailed comments for better understanding.

<body>
  <script type="text/javascript">
    var clicks = 0;
    function onClick() {
      clicks += 1;
      var nextClick = clicks + 1; // Keeping track of the next click
      document.getElementById("clicks").innerHTML = clicks;

      // Checking for specific click counts
      switch (nextClick) {
        case 10:
          // Display a message in div#message.
          document.getElementById('message').innerHTML = 'hello';
          break;

        case 30:
          document.getElementById('message').innerHTML = 'STAHP';
          break;
      }
    };
  </script>
  <button type="button" onClick="onClick()">Add One To Chain</button>
  <p>Chain: <a id="clicks">0</a></p>

  <!-- Container for JS messages -->
  <div id="message"></div>
</body>

Trust this explanation helps!

Answer №5

[Updated]: A better approach for maintainability is to store steps and messages in an object instead of hardcoding them within a switch case loop.

var clicks = 0;
var messages = {"10": "hello", "20": "keep going", "30": "stop"};
function onClick() {
  clicks++;
  document.getElementById("clicks").innerHTML = (messages.hasOwnProperty(clicks.toString())) ? messages[clicks.toString()] : clicks;
  return;      
};

Check out this fiddle

Answer №6

let counter = 0;
const counterElement = document.getElementById("counter");

const messagesList = {
  10: {
    alertText: "Hello"
  },
  20: {
    cssClass: "keep-going",
    message: "Keep Going"
  },
  30: {
    cssClass: "stop",
    message: "Stop !!"
  }
};

document.getElementById("add-one").addEventListener("click", e => {
  counter++;
  let displayMessage = counter;
  counterElement.className = "";
  
  if (typeof messagesList[counter] !== "undefined") {
    const messageObject = messagesList[counter];
    
    if (typeof messageObject.alertText !== "undefined") {
      alert(messageObject.alertText);
    }
    
    if (typeof messageObject.cssClass !== "undefined") {
      counterElement.className = messageObject.cssClass;
    }
    
    if (typeof messageObject.message !== "undefined") {
      displayMessage += " " + messageObject.message;
    }
  }
  
  counterElement.textContent = displayMessage;
});
.keep-going {
  color: green;
}

.stop {
  color: red;
}
<button type="button" id="add-one">Add One To Counter</button>
<p>Counter: <output id="counter">0</output></p>

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

Using JavaScript onChange event with ModelChoiceField arguments

In my Django project, I have a Students model with various fields. I created a ModelChoiceField form allowing users to select a record from the Students table via a dropdown. forms.py: class StudentChoiceField(forms.Form): students = forms.ModelChoic ...

The process of filtering a model stops at the third character and results in an empty output

Whenever I input a value into the 'temp_dollars' model and use a watch property to filter it, the input only retains the first 3 characters and resets. For instance: When I type 123, The model value remains as 123. But wh ...

Tips for sharing a post with an image through the addThis plugin in jQuery

Can anyone help me figure out how to share a post on Facebook using AddThis while including the image and caption? I've written some code to share on Facebook, Twitter, and email but I'm having trouble getting the image to show up. This is what I ...

Displaying JSON keys and values individually on an HTML page

Looking to display a JSON array in HTML using ngFor TypeScript : import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-ng-for', templateUrl: './ng-for.component.html', styleUrls: ['./ng-for ...

Color of the border to be applied on only a

I've been experimenting with view's border style properties to achieve a dynamic partial coloring of a circular shape, but I'm having difficulty making it work. My goal is to create something like this: https://i.sstatic.net/Xb0l7.png http ...

I am having trouble getting Vue.js to function properly within HTML when using Django. Can someone please lend me a

The code run Here is the HTML document: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> <!--javascript extensions--> <script src=' ...

The highest and lowest points of the visible image within a transparent PNG file

As a newcomer to Three.js and graphics in general, I've been on the lookout for a method to identify the highest and lowest visible points in a PNG image with transparency. I understand that graphics manipulation involves manipulating an array of pixe ...

How can I disable a checkbox in AngularJS?

Is there a way to automatically disable a checkbox when selecting an item from the combo box? For example, if "ABONE" is selected, Angular should disable the ABONE checkbox. Note (for example): DefinitionType: ABONE https://i.sstatic.net/vcZpR.png ...

Application unable to save data to file with no indication in error logs

Recently, I've been experimenting with the Capture-Website package, which is designed to save website screenshots to a file. Initially, everything was working smoothly until I decided to restart the server. Now, although my code is running without a ...

Is it possible to invoke a Java Script function from a GridView using `<% Eval("") %>` as a parameter for the function?

Is there a way to call a javascript function with a single parameter from a link click within the GridView Control? I need to pass the value of the parameter using <%Eval("myfield")%>. How can this be accomplished? <ItemTemplate> ...

Why is Jasmine throwing an error when I try to use getElementsByTagName(...)?

HTML: <ul id="listONE"> <li class="{{isSel}}" ng-repeat="person in people" ng-click="selPersonToChange(this)">{{person.name +" - "+ person.city}}</li> </ul> A snippet from my script.js using AngularJS (1.3.1): mymod.control ...

Error: Attempting to access 'map' property of an undefined variable in NEXTJS

I've been struggling to retrieve an image from this API using getStaticProps, but for some reason I can't seem to make it work. In my code snippet, if I add a question mark like this, the console returns 'undefined'. What could be caus ...

How is the script type "text/html" utilized in contemporary applications? Is this specific example regarded as effective usage?

Is it considered good practice in today's standards to utilize something like the following code snippet and use jQuery to swap out content based on a selector? <script type="text/html" id="this-content1"> <h1>This Header Info One</h1& ...

Tips for verifying whether a variable is a node?

Curiosity strikes me: how can I determine if the variable myVar is a node? I could simply check myVar.nodeType, but that might be misleading with something like {nodeType:1} So, naturally, I start to wonder if there's a way to do this instead: myVa ...

Search Box in Motion

I found a fascinating resource on how to create an animated search box using CSS3. The only challenge I'm facing is that I need the position to be set as 'relative'. Instead of having the search box in the center of the screen, I want it pos ...

Creating a dynamic search bar with multiple input fields in HTML

My JSON input for typeahead looks like this: [{"q": "#django", "count": 3}, {"q": "#hashtag", "count": 3}, {"q": "#hashtags", "count": 0}, {"q": "#google", "count": 1}] This is the code I have to implement typeahead functionality: var hashTags = new Blo ...

Activate the current page link in materializecss pagination

I stumbled upon a fantastic pagination plugin for Materializescss UI, available on Github, and it's working like a charm. Now, I am looking to customize this plugin by adding the ability to set the current page and have it highlighted as active. Take ...

The universal CSS variables of Material UI

Creating reusable CSS variables for components can greatly simplify styling. In regular CSS, you would declare them like this: :root { --box-shadow: 0 2px 5px -1px rgba(0, 0, 0, 0.3); } This variable can then be utilized as shown below: .my-class { ...

Manipulate JQuery plug-in properties within an AJAX request using MVC

Currently, I am utilizing a Jquery time picker sourced from Within the view, there exists this time picker control. $("#startTime").timePicker({ startTime: "09.00", endTime: new Date(0, 0, 0, 19, 0, 0), show24Hours: false, ...

What is the functionality of array equals useState declarations in JavaScript?

Within ReactJS functional components, the following line enables the creation of: A variable to keep track of the current count A method to update the state when invoked Here's an example in JavaScript: let [count, setCount] = useState([]); Can you ...