Sling Academy
Home/JavaScript/Use Typed CSS Values with the CSS Typed OM in JavaScript

Use Typed CSS Values with the CSS Typed OM in JavaScript

Last updated: December 12, 2024

The CSS Typed Object Model (Typed OM) is a W3C standard introduced to enhance how developers interact with CSS in JavaScript. By using Typed CSS Values, it offers an interface that allows manipulating CSS with greater precision and efficiency than the traditional CSSOM methods which handle all styles as untyped strings.

Understanding CSS Typed OM

The CSS Typed OM is a significant improvement because it allows the properties, such as lengths, percentages, and transforms, to be manipulated as strongly typed objects rather than raw strings. This leads to more accurate calculations and manipulations, and makes the codebase easier to understand and maintain.

Features of CSS Typed OM

  • Typed Values: Instead of stringified CSS, you work with strong types like CSSUnitValue, CSSNumberValue, etc.
  • Precision: Allows for higher precision in layout calculations, eliminating issues with parsing properties as strings.
  • Readability: The API is designed to be more intuitive and easier to read compared to traditional methods.
  • Performance: Parsing strings is expensive, but with typed values, this overhead is reduced.

Working with CSS Values

Typed OM provides various CSS interfaces for dealing with different value types. Here is how you can easily create and manipulate these objects:

CSSUnitValue Example

The CSSUnitValue allows you to work with lengths and percentages more seamlessly.

const element = document.querySelector('.my-element');
const computedStyles = getComputedStyleMap(element);

// Getting a CSSUnitValue for 'width'
const widthValue = computedStyles.get('width');
console.log(widthValue); // Example Output: CSSUnitValue {value: 100, unit: "px"}

// To add 20 pixels more to the width
widthValue.value += 20;
element.attributeStyleMap.set('width', widthValue);

CSSNumberValue Example

This example shows how to use CSSNumberValue for properties such as opacity:

const element = document.querySelector('.my-element');
const attributeStyles = element.attributeStyleMap;

// Assuming current opacity is 0.5
let opacityValue = attributeStyles.get('opacity');
console.log(opacityValue); // CSSNumberValue {value: 0.5}

opacityValue.value *= 2; // To change opacity to 1 (full opacity), 
op.value = Math.min(opacityValue.value, 1); // Keeping it clamped between 0 to 1
attributeStyles.set('opacity', opacityValue);

Transforming Elements with CSSMathValue

The CSSMathValue is excellent for doing calculations on CSS values. Here's how you can make linear transformations with it:

const rotateValue = new CSSTransformValue([
  new CSSRotate(CSS.deg(90))
]);

element.attributeStyleMap.set('transform', rotateValue);

Benefits and Conclusion

The Typed OM makes styles more accessible and manipulation far less error-prone. Furthermore, it eliminates the need for tricks such as creating temporary divs or measuring with JavaScript for calculations.

Another advantage is unit interoperability. A CSSUnitValue can automatically handle conversions for you, making it easier to work with different units where applicable.

Overall, by reducing the overhead of parsing and converting CSS between JavaScript and string operations, using typed CSS properties allows web applications to use direct CSS manipulation which increases both performance and clarity. As the CSS Typed OM gains more traction and becomes better supported by browsers, developers are encouraged to adopt it in their modern project solutions.

Next Article: Bridge CSS and JavaScript via the CSS Typed OM

Previous Article: Refine Inheritance Using the CSS Properties and Values API in JavaScript

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration