javascriptcssfirefox

Is there a Firefox-compatible way to modify @properties using Javascript?


I like to use CSS @properties in my websites. Unfortunately, these don't play well with JavaScript in Firefox; the standard way to modify them is document.documentElement.attributeStyleMap.set('--attributeName', 'value'), and Firefox doesn't support attributeStyleMap (and probably never will, given that this has been a known issue for 9+ years.)

Does anyone know an alternative way to modify @attributes using JavaScript?


Solution

  • Firefox supports the HTMLElement style interface. It uses only strings (so no typed values) and doesn't auto-expand style properties (e.g., margin to margin-top, margin-right, etc.).

    Your example

    document.documentElement.attributeStyleMap.set('--attributeName', 'value')
    

    sets a variable --attributeName in an inline style attribute. The way to do it using the style interface is

    document.documentElement.style.setProperty( '--attributeName', 'value' );
    

    For more conventional CSS properties, values can be simply assigned. For example:

    document.documentElement.style.color = 'red';
    document.body.style.marginTop = '10px';
    

    Notice that margin-top becomes camel-case marginTop.