Major_Ash
Major_Ash

Reputation: 309

Accessing html attributes in css keyframes animations

I have this horizontal chart in which each bar should take the width that is present in the corresponding div tags.

This is the index.html

<section class="chart">
  <div class="chart-entry">
    <span class="brand">Apple</span>
    <div class="bar" data-percentage="74%"></div>
  </div> 
  <div class="chart-entry">
    <span class="brand">Mango</span>
    <div class="bar" data-percentage="87%"></div>
  </div> 
  ...
</section>

The style.css part

.chart .bar {
  background-color: rgb(58, 55, 40);
  animation: show-bar 3.2s 1.6s forwards;
} 

@keyframes show-bar {
  0% {
    width: 0;
  }
  100% {
    width: /*** The variable where the data-percentage should be present ***/;
  }
}  

I am new to Css and do not have a good idea about animations so it was difficult to understand from someone else's post here on Stack. Would really appreciate any suggestion.

Upvotes: 1

Views: 1289

Answers (2)

IamFlok
IamFlok

Reputation: 64

How about this solution:

In @keyframes, set width to auto on 100%; In the html, I believe you will have the percentage value coming dynamically. You could inline max-width value equal to data-percentage. You may not even need data-percentage attribute if you only want to display it as a progress bar.

<div class="bar" data-percentage="74%" style="max-width:74%"></div>

Alternatively, use https://www.w3schools.com/tags/tag_progress.asp

and give your bar a height to display:

.chart .bar {
  background-color: rgb(58, 55, 40);
  animation: show-bar 3.2s 1.6s forwards;
  height: 15px;
} 

see working code: https://jsfiddle.net/qvyjwzpu/

Upvotes: 2

Titulum
Titulum

Reputation: 11476

While you can not directly set the width of the keyframes, you can use another solution that uses the data-percentage attribute to set the bar widht:

setTimeout(() => {
  const bars = [...document.getElementsByClassName('bar')];

  bars.forEach(bar => {
    const percentage = bar.getAttribute('data-percentage');
    bar.style.width = `${percentage}`;
  });
}, 500);
.chart {
  width: 500px;
  background-color: lightgray;
  padding: 15px;
}

.chart-entry {
  position: relative;
  width: 500px;
  height: 20px;
  background-color: white;
  margin-bottom: 15px;
}

.brand,
.bar {
  position: absolute;
  height: 100%;
}

.brand {
  z-index: 2;
  width: 100%;
  color: red;
}

.bar {
  background-color: pink;
  z-index: 1;
  transition: 1s;
  width: 0;
}
<section class="chart">
  <div class="chart-entry">
    <span class="brand">Apple</span>
    <div class="bar" data-percentage="74%"></div>
  </div>
  <div class="chart-entry">
    <span class="brand">Mango</span>
    <div class="bar" data-percentage="87%"></div>
  </div>
</section>

Upvotes: 1

Related Questions