Display a div in a specific color depending on whether the value is positive or negative, and

I created a counter but I want to change the color of the id="clicks" based on whether the value is positive or negative, and also add text accordingly.

     var clicks = 0;
    function clickplus() {
        clicks += 1;
        document.getElementById("clicks").innerHTML = clicks;
 }
  var clicks = 0;
    function clickless() {
        clicks -= 1;
        document.getElementById("clicks").innerHTML = clicks;
 }
         #btn_plus{
  background-color: #04AA6D; /* Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;}
   #btn_less{
  background-color: red; /* Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;}
<body style="background-color:#F0F0F0">
  <center>
    </br></br></br>
    <h1>
      <p style="color:#002244">COUNT: <a id="clicks">0</a></p>
    </h1>
    <button id="btn_plus" type="button" onClick="clickplus()">+1</button>
    <button id="btn_less" type="button" onClick="clickless()">-1</button>
    </center>
    </body>

Is there anyone who can assist? Change the color of id="clicks" to red if the value is negative, green if it's positive, and display the text positive/negative accordingly.

Answer №1

Utilize

document.getElementById("clicks").style.color = color;

<body style="background-color:#F0F0F0">
<center></br></br></br><h1><p style="color:#002244">CONTAGEM: <a id="clicks">0</a></p></h1>
<button id="btn_plus" type="button" onClick="clickplus()">+1</button>
<button id="btn_less" type="button" onClick="clickless()">-1</button>

    
    </center>
    </body>
    <script>
    var clicks = 0;
    function setColorAndText(clicks){
      let color = (clicks<0)?"red":(clicks>0)?"green":"black";
      let appendText = (clicks<0)?"negative":(clicks>0)?"positive":"";
      document.getElementById("clicks").innerHTML = clicks + " " + appendText;
      document.getElementById("clicks").style.color = color;
    }
    
    function clickplus() {
        clicks += 1;
        setColorAndText(clicks);    
    }
  
    function clickless() {
        clicks -= 1;
        setColorAndText(clicks);           
    }
    </script>
    
    <style>
         #btn_plus{
  background-color: #04AA6D; /* Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;}
   #btn_less{
  background-color: red; /* Green */
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;}
    </style>

Answer №2

Check out this updated script utilizing delegation, eventListener, and appropriate CSS styling (avoiding the deprecated center)

I've also rearranged the buttons since it's more common for people to associate negative values with positions to the left of zero

const container = document.getElementById('centerDiv');
const clickCounter = document.getElementById('clicks');
const posNeg = document.getElementById('posneg');
let clicks = 0;

const clickAction = (e) => {
  let target = e.target.closest('button.btn');
  if (!target) return; // not one of the buttons
  let increment = target.id === 'btn_plus' ? 1 : -1;
  clicks += increment;
  clickCounter.textContent = clicks;
  posNeg.classList.toggle('neg', clicks < 0);
  posNeg.classList.toggle('pos', clicks > 0);

};

container.addEventListener('click', clickAction);
body {
  background-color: #F0F0F0
}

#centerDiv {
  max-width: fit-content;
  margin-left: auto;
  margin-right: auto;
  text-align: center;
}

.btn {
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}

#btn_plus {
  background-color: #04AA6D;
  /* Green */
}

#btn_less {
  background-color: red;
}

.pos::after {
  color:  #04AA6D;
  content: 'Positive'
}
.neg::after {
  color: red;
  content: 'Negative'
}
<div id="centerDiv">
  <h1>
    <p id="counter" style="color:#002244">COUNT: <a id="clicks">0</a> <span id="posneg"></span></p>
  </h1>
  <button id="btn_less" class="btn" type="button">-1</button>
  <button id="btn_plus" class="btn" type="button">+1</button>
</div>

Answer №3

To implement a styling feature in your HTML document, you can start by defining a CSS class named .negative with the property color: red. This class will be used to dynamically change the text color based on certain conditions. By utilizing the element.classList.toggle() method, you can easily toggle the presence of this class depending on whether the value meets specific criteria. Additionally, pseudo-elements like ::after can also be employed through CSS to enhance the visual presentation of elements.

let total = 0;

const BUTTONS_LIST = document.querySelectorAll('button');

BUTTONS_LIST.forEach(button => {
  button.addEventListener('click', function() {
    switch (this.id) {
      case 'btn_increase':
        total++;
        break;
      case 'btn_decrease':
        total--;
        break;
    }
    currentValue.value = count;
    currentValue.classList.toggle('negative', (count < 0));
  })
})
body {
  background-color: #EFEFEF;
  margin-top: 4rem;
}

div{
  color: #112233;
  font-size: 2.1em;
  font-weight: 800;

  output {
    color: navy;
    &.negative {
      color: red;
      &::after {
        content: ' negative';
      }
    }
    &::after {
      content: ' positive';
    }
  }
}

#btn_increase {
  background-color: #23AB56;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}

#btn_decrease {
  background-color: crimson;
  border: none;
  color: white;
  padding: 15px 32px;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  font-size: 16px;
}
<body style="background-color:#F0F0F0">
    <div>TOTAL: <output id="currentValue" role="spinbutton">0</output></div>
    <button id="btn_increase" type="button">+1</button>
    <button id="btn_decrease" type="button">-1</button>
</body>

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

Move the container all the way to the left

On my page, I have a grey section with the heading 'Start Analysis' that needs to be shifted to the left along with all its contents. How can this be achieved? The HTML code for the section is as follows: <!DOCTYPE html> <html lang="en ...

Creating a separate CSS file for a CSS class that sets the width of a <div

I am looking to enhance a div element by incorporating a specific class from a separate CSS file. For example, my HTML file contains the following snippet: /* width 90% */ @media (min-width: 960px) { div.width90 { max-width: 90%; } } <div cl ...

Transferring data between Django and JavaScript: dealing with DateTime information

I'm facing an issue while attempting to transfer data (step_count_data) from Django to a JavaScript function. Below is the code snippet: Django #somecode step_count_date.append(str(step_count_list[i].startTime.date())) context = {'step ...

Unexpected Issues with Page Refresh in AngularJS

I am currently working on an Angular application using the MEAN stack. Here's a scenario: imagine you have an express route that queries the database and sends the results back in the response: app.get('/api', function(req, res){ Todo.f ...

Exploring the creation of a WebGL viewer by utilizing Three.js in conjunction with ColladaLoader.js

I am in the process of setting up a WebGl viewer using three.js + colladaloader.js, but I'm encountering some difficulties when attempting to import and visualize my own collada object. The example loads correctly, however, when I try to incorporate m ...

core.js:15723 ERROR TypeError: Unable to access the 'OBJECT' property because it is undefined

Whenever I attempt to run this function, I encounter an issue. My goal is to retrieve the latitude and longitude of an address from Google's API. This error message pops up: core.js:15723 ERROR TypeError: Cannot read property 'geometry' of ...

Creating a Responsive Design with Bootstrap 4 - Adjustable Height Structure

I am facing an issue with my website built on Bootstrap 4. I am trying to make a layout that utilizes the full height of the screen. I had expected the new "flex" grid system in Bootstrap 4 to facilitate this, but it seems like I might be implementing it i ...

Determine the viral coefficient based on the sharing platform being used, whether it is Facebook or Twitter

Traditionally, the viral coefficient is measured through email addresses. For example, if a current user [email protected] invites 10 people via email, you can track how many signed up and calculate the viral coefficient based on that. But what if th ...

Dealing with errors in AngularJS factory servicesTips for managing errors that occur

Factory code app.factory('abcFactory', function ($http, Config, $log) { var serviceURL = Config.baseURL + '/results'; return{ results:function() { var promise = $http({ method: 'GET&apos ...

Working with MongoDB collections in JavaScript to extract and manipulate array data

I have successfully parsed this array using a for loop You can view the results in the console log below. https://i.sstatic.net/zxBna.png When handling role_code in JavaScript, the following code snippet can be used: for (doctor in data.user.userType){ ...

Position your Logo to the left, align the Menu in the center, and place top links on the right using Bootstrap

I am currently struggling to create two rows with the logo aligned to the left, 'Home' and 'User' menu links at the top right corner, and a second row displaying 'Link1', 'Link2', 'Link3' menus centered. Th ...

Creating a column heading that appears at the top of each column break with the help of CSS column-count

Is there a way to output a list into x number of columns within a content div without specifying the exact amount of columns in CSS? I also want to include a heading at the top of each column: Firstname Lastname State Firstname Lastname State ...

The GridCalendar view of FullCalendar v6.1 is generating 50 `ARIA attribute unsupported or prohibited` errors when analyzed with the SiteImprove browser extension

The Challenges Creating a website that adheres to accessibility laws can be quite daunting. I am currently using SiteImprove, a free browser extension, to check for any issues on my site. Unfortunately, the GridCalendar view is showing 50 errors. ARIA a ...

Unable to adjust offset/repeat of texture being utilized as alphaMap

demo: the alphaTexture is being modified in its offset with each render. When used as a "map" property, the offset changes, but when used as an "alphaMap" it remains static. This issue arises with the second mesh's alphaMap. relevant code from demo ...

Issues with Angular Component not detecting changes in @Input array

I'm dealing with a challenging setup where: The Parent Service (A) is imported in the Parent Component (B). Then, the Parent Component passes an array of Objects to a Child Component (C), which are referenced from the Parent Service (e.g. <child-c ...

Using Sencha Touch for asynchronous HTTP request to Model-View-Controller

Ext.util.JSONP.request({ url: '/Home/GetMessagesMobile', callbackKey: 'callback', params: { lat: geoip_latitude(), lng: geoip_longitude(), ...

Is it possible for Bootstrap to hide a grid column on extra small screens by setting its column width to zero?

Is there a specific Bootstrap class that allows me to hide a grid column for certain screen sizes without using media queries and the "display:none" style? ...

What is the best way to fill an array within an object using React Hooks?

I am encountering an issue with an object that includes an array. Here is the code snippet in question: const [data, setData] = useState({ jobs: [] }); Currently, I am retrieving data from an API and need to append this fetched information to the jobs arr ...

Uncovering the Power of Shadow DOM within HTML

Lately, I've noticed a lot of buzz surrounding Shadow DOM. During a video I watched about the launch of Angular 2, the speaker kept mentioning Shadow DOM without much explanation. Can someone clarify what exactly Shadow DOM refers to? ...

Cross-browser compatible (Chrome, Internet Explorer, Firefox)

I'm having trouble understanding why this script is not functioning correctly in Internet Explorer, although it works fine in Firefox and Chrome. Whenever I attempt to run the script in IE, I receive an error message stating "ACTIVEX stop script". An ...