Search code examples
htmlcsscss-animations

Is there a way to convert a string into an int in css?


So, I'm making a loading screen where each dot of the "loading..." has a data-dotnum in the html. I want to position each dot on the loading so I can have it look normal at the beginning but still be able to manipulate individual dots. I'm using calc() to get where it should go at the beginning (I'll figure out the correct spacing later.) I don't think that javascript can get attributes, but maybe it can, so please say that (and how to do it) if javascript can get data attributes from html.

The HTML is:

<div class="loadingText">
  <h1 class="mainline">Loading</h1>
  <h1 class="dot" data-dotnum="1">.</h1>
  <h1 class="dot" data-dotnum="2">.</h1>
  <h1 class="dot" data-dotnum="3">.</h1>
</div>

As you can see, each dot has the same class, so I cannot select them by class. If I have to I could change each to have a different class, but for the simple loading animation I am thinking of, I think just calculating its position using what its number is would be easier.

The CSS is:

h1 {
  position: absolute;
  margin-bottom: 0;
}

.dot {
  left: calc(122px + calc(attr(data-dotnum) * 30px));
}

And that's where the problem comes in. using "attr(data-dotnum)" returns a string, and calc() can't multiply a string by 30. I want to know if there is a property that can change the string to be an int.


Solution

  • You can use css variables.

    h1 {
      position: absolute;
      margin-bottom: 0;
    }
    
    .dot {
      left: calc(122px + calc(var(--data-dotnum) * 30px));
    }
    <div class="loadingText">
      <h1 class="mainline">Loading</h1>
      <h1 class="dot" style="--data-dotnum:1;">.</h1>
      <h1 class="dot" style="--data-dotnum:2;">.</h1>
      <h1 class="dot" style="--data-dotnum:3;">.</h1>
    </div>