javascriptcsscss-houdini

Houdini - CSS Typed OM: How to get a value of a defined property through javascript


Usecase

I have the custom property '--animation-duration' defined as an time value with the new 'registerProperty' function:

CSS.registerProperty({
  name: '--animation-duration',
  syntax: '<time>',
  inherits: false,
  initialValue: '1s'
});

In my CSS, I can now add this property to my class and adjust it's value:

.my-el {
  --animation-duration: 1.5s;
}

Now I want to get the value of this property on my element trough javascript, always in ms. This can be achieved by the following line of code:

const duration = CSSNumericValue.parse(getComputedStyle(el).getPropertyValue('--ripple-anim-duration')).to('ms').value; // 1500

Question

Is there a shorter/better way of getting this value in my general javascript?


Extra

I know you can do it shorter in a worklet (tested in the paint-worklet):

const duration = properties.get('--ripple-anim-duration').to('ms').value; // 1500

And that following code is not working in my general javascript:

const duration = el.attributeStyleMap.get('--ripple-anim-duration').to('ms').value; // ¯\_(ツ)_/¯

Solution

  • This is the normal way el.computedStyleMap().get('--ripple-anim-duration').to('ms').value

    1. You don't need to use CSSNumericValue.parse
    2. attributeStyleMap working for properties defined in style attribute

    I've wrote a few posts about Custom Properties and Values, if you're interested: