TIAS
TIAS

Reputation: 43

How to specify starting value of <meter> tag not from zero?

Suppose, I want to specify (highlight) the range of meter tag from 0.4 to 0.6 values. How can I do that?

<meter max="0.6" min="0.4"></meter>

I want to do something like this:

Meter with range

Upvotes: 3

Views: 90

Answers (2)

Lajos Arpad
Lajos Arpad

Reputation: 76943

You can set the background of your meter, in our case it has a lightgray color up to 40%, changes to green and keeps it that way up to 60% from whence it turns to lightgray again.

meter {
  background: linear-gradient(
    90deg,
    lightgray 40%,
    green 40%,
    green 60%,
    lightgray 60%
  );
  border-radius: 10px;
  border: 1px solid grey;
}
<meter id="fuel" min="0" max="100" low="33" high="66" optimum="80" value="0">at 50/100</meter>

You can also programmatically change it, like here

let state = {
    lower: 40,
    greater: 60
}

function change(what, how) {
    state[what] += how;
    let {lower, greater} = state;
    document.getElementById("fuel").style.background = `
    linear-gradient(
        90deg,
        lightgray ${lower}%,
        green ${lower}%,
        green ${greater}%,
        lightgray ${greater}%
    )
    `;
}
#fuel {
  background: linear-gradient(
    90deg,
    lightgray 40%,
    green 40%,
    green 60%,
    lightgray 60%
  );
  border-radius: 10px;
  border: 1px solid grey;
}
<input type="button" value="<" onclick="change('lower', -1)">
<input type="button" value=">" onclick="change('lower', 1)">
<meter id="fuel" min="0" max="100" low="33" high="66" optimum="80" value="0">at 50/100</meter>
<input type="button" value="<" onclick="change('greater', -1)">
<input type="button" value=">" onclick="change('greater', 1)">

Each time you click an arrow, the lower bound changes if one of the first two is the one you clicked, otherwise the greater bound will be changed.

Upvotes: 1

Ian
Ian

Reputation: 11

You can replicate a meter with some simple HTML and styling, then just change their values with JS later on:

.meter {
  width: 200px;
  background-color: rgb(0, 0, 0, 0.2);
  border-radius: 5px;
  position: relative;
  height: 8px;
  margin-left: 10px;
  margin-right: 10px;
}

.filled {
  height: 100%;
  background-color: green;
  border-radius: 5px;
  position: absolute;
  left: 20%; /* Starting point */
  width: 30%; /* Fill percentage */
}
<div class="meter">
  <div class="filled"></div>
</div>

Upvotes: 1

Related Questions