Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Changing color based on gauge value – Javascript

I’m trying to write a Javascript function to go alongside a gauge that I copied online, the gauge works like this:

const gaugeElement = document.querySelector(".gauge");

function setGaugeValue(gauge, value) {
  if (value < 0 || value > 1) {
    return;
  }

  gauge.querySelector(".gauge__fill").style.transform = `rotate(${value / 2}turn)`;
  gauge.querySelector(".gauge__cover").textContent = `${Math.round(value * 100)}%`;

}

setGaugeValue(gaugeElement, 0.26);
<div class="card">
  <div class="FuelLevelText">
    <h3>Fuel Level</h3>
  </div>
  <div class="gauge">
    <div class="gauge__body">
      <div id="gaugecolor" class="gauge__fill"></div>
      <div class="gauge__cover"></div>
    </div>
  </div>
</div>

There’s also a bit of CSS that goes with this

This works fine to change the gaugeElement value and will change the percentage on screen, however I’d like to add a rule so if the value goes below 0.05 or 5% the gauge fill background-color turns red to indicate it’s running low. I’m very very new to coding so I’m struggling to find a resource online that has something similar to what I need that I can adapt to my needs.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I tried adding a line:

if (gaugeElement, '< 0.05') {
    function changebackground(color) {
        #gaugecolor = color;
    }

    changebackground('red');
}

However I don’t know enough Javascript to know if this is even targeting the right section?

>Solution :

If the value goes below 0.05 or 5% the gauge fill background-color turns red.


const gaugeElement = document.querySelector(".gauge");

function setGaugeValue(gauge, value) {
  if (value < 0 || value > 1) {
    return;
  }

  gauge.querySelector(".gauge__fill").style.transform = `rotate(${value / 2}turn)`;
  gauge.querySelector(".gauge__cover").textContent = `${Math.round(value * 100)}%`;

  if (value < 0.05) {
    gauge.querySelector(".gauge__fill").style.backgroundColor = 'red';
  } else {
    gauge.querySelector(".gauge__fill").style.backgroundColor = ''; // Reset the background color
  }
}

setGaugeValue(gaugeElement, 0.26);

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading