Varun Nuthalapati Varun Nuthalapati - 4 months ago 8
Javascript Question

Display the value of CSS property in HTML using JavaScript

I implemented a progress bar using HTML and CSS. The value of the progress bar depends on the width of the inner class (in this code: bar-fill). I want to access this width property in my styling and display it next to the progress bar.

Working Code: https://jsfiddle.net/nvarun123/h5xgfyrp/3/

HTML code:

<div class="container">
<div class="bar">
<span class="bar-fill"></span>
</div>
</div>


CSS code:

.container{
width:300px;
}
.bar{
width:100%;
background-color: #E3E3E3;
border-radius:10px;
}

.bar-fill{
height:15px;
display:block;
background:#0073CF;
width:60%;
border-radius:7.5px;
-webkit-transition: width 0.8s ease;
transition: width 0.8s ease;
}

Answer

▶ First, you need to add an HTML element that will show the progress:

<div id = "progress"></div>

▶ Then, you can use the following JavaScript code:

var
    /* The elements */
    bar = document.getElementsByClassName("bar")[0],
    barFill = document.getElementsByClassName("bar-fill")[0],
    progress = document.getElementById("progress"),

    /* The bar's total width */
    barWidth = window.getComputedStyle(bar, null).getPropertyValue("width"),

    /* How much of the bar is filled */
    barFillWidth = window.getComputedStyle(barFill, null).getPropertyValue("width"),

    /* Create the percentage */
    pct = 100 * (parseFloat(barFillWidth) / parseFloat(barWidth)) + "%";

/* Set the innerHTML of our progress element */
progress.innerHTML = pct;

Check out this fiddle or the following snippet for a visual representation.

Snippet:

var
  bar = document.getElementsByClassName("bar")[0],
  barFill = document.getElementsByClassName("bar-fill")[0],
  progress = document.getElementById("progress"),
  barWidth = window.getComputedStyle(bar, null).getPropertyValue("width"),
  barFillWidth = window.getComputedStyle(barFill, null).getPropertyValue("width"),
  pct = 100 * (parseFloat(barFillWidth) / parseFloat(barWidth)) + "%";

/* Set the innerHTML of #progress */
progress.innerHTML = pct;
.container {
  width: 300px;
}

.bar {
  width: 100%;
  background-color: #E3E3E3;
  border-radius: 10px;
}

.bar-fill {
  height: 15px;
  display: block;
  background: #0073CF;
  width: 60%;
  border-radius: 7.5px;
  -webkit-transition: width 0.8s ease;
  transition: width 0.8s ease;
}
<div class="container">
  <div class="bar">
    <span class="bar-fill"></span>
  </div>
</div>
<div id="progress"></div>