CSSInDepth/css-in-depth

Extraneous JS code in ch02/listing-2.31.html

Closed this issue · 2 comments

In ch02/listing-2.31.html the statement rootElement = document.documentElement; is extraneous. rootElementis already/still set by the preceding let rootElement = document.documentElement;

That’s actually done on purpose. In the book, that JavaScript is shown in two separate listings (2.30 and 2.31). I explain each set (lines 68–71 and 73–74) individually in the text. I defined rootElement both times so each listing in the book make sense on its own.

However, they are intended to be executed together, so I put them both in the same file in this repository. Since the duplicated line does no harm, I kept it in place so the code here exactly matches that in the book.

It’s not a perfect solution, though. I’m open to other ideas how to present it. What would make the most sense to you as a reader?

To be honest it didn't even register as a two-in-one listing at the time - so you may have a point. You may find the following variation a bit clumsy:

Listing 2.30 Accessing a custom property in JavaScript

  <script type="text/javascript">
    let rootElement = document.documentElement,
        styles = getComputedStyle(rootElement),
        mainColor = styles.getPropertyValue('--main-bg');

    console.log(String(mainColor).trim());

    // continued in next listing ...

Listing 2.31 Setting a custom property in JavaScript

    // ... continued from previous listing
    rootElement.style.setProperty('--main-bg', '#cdf');
  </script>