Notes on Day 3 of 30 Days of JavaScript

This is my first time to encounter variables in native CSS. The lesson was exciting and I learned a lot!

Table of Contents

Lessons Learned

CSS variables

Also know as “Custom Properties”, these enables the use of variables to assign CSS styles. Fortunately it is widely implemented now in most modern browsers.

For organizational purpose, the :root pseudo-class can be used to declare common styles.

:root {
  --boxPadding: 16px;
  --baseColor: #000000;
  --accentColor: #FCFCFC;
  ...
  --myCustomName: ...  
}

and these can be used alongside standard CSS inside style blocks with the use of var():

.box-container {
  display: block;
  padding: var(--boxPadding);
  border-radius: 8px;
  border: 1px solid var(--accentColor);
  ...
}

Lastly, since this is CSS, their values can also be overriden if re-declared or re-assigned afterwards inside the file.

NodeList.prototype.forEach

I know forEach is available for array objects but I didn’t know the NodeList object had this in its prototype. This is covenient for skipping transforming into an array.

const spanList = document.querySelectorAll('span')
// NodeList(5) [span, span, span.cm-variable, span.cm-property, span.cm-variable]

spanList.forEach(span => console.log(span))
// <span>...</span>

HTMLElement: change event

This event is available for common form elements such as <input> and <textarea> wherein it listens for the changes in the elements’ values.

<input type="email" name="email" />
<p id="info">Logged in as <span></span><p>
const email = document.querySelector('input[type="email"]')
const message = document.querySelector(p#info span)

const showMessage = (event) => {
  message.textContent = event.target.value
}

email.addEventListener('change', showMessage)

Element: mouseover event

This event fires when a cursor is within the scope of an element or its children.

HTMLElement.dataset

We can declare custom data attributes inside DOM elements that are accessible using the dataset keyword. Accessing this would return a DOMStringMap object.

<textarea rows="1" data-show="false" data-test="list-page" data-original-title="null"></textarea>
console.log(document.querySelector('textarea'))

{
  "show": "false",
  "test": "list-page",
  "originalTitle": "null"
}

CSSStyleDeclaration.setProperty()

I didn’t know this generalized method existed because all I did before was to set the individual styles as is!

In my defense, I rarely set CSS properties using JS directly because if we can do it through setting selector then this would be the last resort of implementation.

const story = document.querySelector('p.story')
// These both set the text color to red 
story.style.color = 'red'
story.style.setProperty('color', 'red')

References

Twitter, LinkedIn