Categories
JavaScript Answers

How to Declare Static Constants in JavaScript ES6 Classes?

Sometimes, we may want to declare static constants in our JavaScript classes.

In this article, we’ll look at how to declare static constants in ES6 JavaScript classes.

Add Getters in Our Class

To declare static constants in our ES6 classes, we can declare constants outside the class and add getters that return the constants in our class.

For instance, we can write:

const constant1 = 3,
  constant2 = 2;
class Example {
  static get constant1() {
    return constant1;
  }

  static get constant2() {
    return constant2;
  }
}

console.log(Example.constant1)
console.log(Example.constant2)

We declare constant1 and constant2 .

Then in the Example class, we create the constant1 and constant2 getters.

We add the static keyword before get so that we can make the static.

Then in the getter function, we return the constant1 and constant2 values respectively.

Likewise, we can write:

class Example {
  static get constant1() {
    return 3
  }

  static get constant2() {
    return 2
  }
}

Object.freeze(Example);
console.log(Example.constant1)
console.log(Example.constant2)

which is equivalent to what we have written above.

So when we log the values of Example.constant1 and Example.constant2 , we see 3 and 2 respectively.

Object.freeze

We can freeze the class to make the whole class immutable.

To do this, we write:

class Example {}
Example.constant1 = 3
Example.constant2 = 2
Object.freeze(Example);
console.log(Example.constant1)
console.log(Example.constant2)

We add our static properties with:

Example.constant1 = 3
Example.constant2 = 2

This works since classes are constructor functions, which are objects.

This also means we can use the Object.freeze method on Example to make the Example class immutable.

So we can log the values of the Example.constant1 and Example.constant2 properties and get their values.

We should see 3 and 2 respectively.

Conclusion

We can declare static constants in our JavaScript class by declaring static getters that returns constants declared outside the class.

Also, we can freeze the class with the Object.freeze method since it’s a regular object.

This makes the class immutable.

Categories
JavaScript Answers

How to Resize HTML5 Canvas to Fit the Window with JavaScript?

Sometimes, we may want to resize an HTML5 canvas to fit the window that it’s in with JavaScript.

In this article, we’ll look at how to resize an HTML5 canvas to fit the window with JavaScript.

Setting the width and height Properties of the Canvas

We can just set the width and height properties of the canvas as the window resizes to set the width and height of the canvas to change its size.

For instance, we can write:

const draw = (canvas) => {
  const ctx = canvas.getContext("2d");
  ctx.beginPath();
  ctx.arc(95, 50, 40, 0, 2 * Math.PI);
  ctx.stroke();
}

const canvas = document.querySelector("canvas");
canvas.width = window.innerWidth
canvas.height = window.innerHeight
draw(canvas)

window.addEventListener('resize', () => {
  canvas.width = window.innerWidth
  canvas.height = window.innerHeight
  draw(canvas)
})

to change the size of the canvas initialize to the window’s dimensions with:

canvas.width = window.innerWidth
canvas.height = window.innerHeight

And we do the same thing in the resize event listener, which we added with the addEventListener method.

When the canvas resizes the content disappears, so they have to be drawn again whenever we resize the canvas by setting the width and height properties.

Set the Size with CSS

We can also set the size of the canvas with CSS to make it fill the screen.

For instance, we can write the following HTML:

<canvas></canvas>

And the following CSS:

html,
body {
  width: 100%;
  height: 100%;
  margin: 0;
}

canvas {
  background-color: #ccc;
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
}

to set the canvas’s width and height both to 100%.

We also set the position to absolute and top , left , right , and bottom to 0 to make the canvas fill the screen.

Also, we make the html and body elements fill the screen by setting the width and height to 100%.

And we can draw on it with:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();

We draw a circle with the arc method.

We have the center x and y coordinates, radius, and start and end angles in radians as arguments in this order.

Conclusion

We can resize the canvas to fit the screen with JavaScript or CSS.

Categories
JavaScript Answers

How to Format a Date as an ISO-8601 String with Moment.js and JavaScript?

Sometimes, we may want to format a date into the IS0–8601 standard format and JavaScript.

In this article, we’ll look at how to format a date into an ISO-8601 string with moment.js and JavaScript.

The toISOString Method

Moment.js comes with the toISOString method to let us format dates to ISO-8601 format.

For instance, we can write:

console.log(moment(new Date(2021, 1, 1)).toISOString())

Then we get:

'2021-02-01T08:00:00.000Z'

as a result.

The format Method

The format method also lets us format a date to an ISO-8601 date string.

For instance, we can write:

import moment from "moment";
console.log(moment(new Date(2021, 1, 1)).format());

Then we get the same result as before.

Timezone Support

We can use the Moment Timezone library to add support for time zones.

Then we can set the time zone in our app and then use the toISOString method to convert the moment object to an ISO-8601 string.

For instance, we can write:

const moment = require("moment-timezone");
moment().tz("America/Los Angeles");
console.log(moment(new Date(2021, 1, 1)).toISOString(true));

Then the console log logs:

'2021-02-01T00:00:00.000-08:00'

as a result.

Parsing ISO-8601 Dates

We can parse ISO-8601 dates with moment.js

For instance, we can write:

import moment from "moment";
console.log(moment("2021-01-01", moment.ISO_8601));

We pass in a date string in ISO-8601 format.

And we pass in the moment.ISO_8601 constant to let moment know that the date string in the first argument is an ISO-8601 date.

Conclusion

We can create and parse ISO-8601 date strings with moment.js in our JavaScript code.

Categories
JavaScript Answers

How to Get a CSS Property Value of an Element with JavaScript?

Sometimes, we may want to get a CSS property value of an element with JavaScript.

In this article, we’ll look at how to get a CSS property value of an element with JavaScript.

Use the window.getComputedStyle Method

We can use the window,getComputedStyle method to get the computed CSS styles of an element.

For instance, if we have the following HTML:

<div style='height: 300px; overflow-y: auto'>

</div>

Then we can write the following JavaScript:

const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

const style = window.getComputedStyle(div);
const height = style.getPropertyValue('height');
console.log(height)

to add some content to the div.

We have the for loop to add 100 p elements into the div with document.createElement .

Then we set the textContent of each element to add some content.

And then we call div.appendChild to add the p elements as children of the div.

Next, we call window.getComputedStyle with the div to get a style object.

And then we can get the height property with:

const height = style.getPropertyValue('height');

And height is '300px' since we set it as such in the HTML.

Use the Element’s computedStyleMap Method

Also, we can use the computedStyleMap method that comes with elements to get the styles applied to the element.

For instance, we have the following HTML:

<div style='height: 300px; overflow-y: auto'>

</div>

And we can write the following JavaScript:

const div = document.querySelector('div')
for (let i = 1; i <= 100; i++) {
  const p = document.createElement('p')
  p.textContent = i
  div.appendChild(p)
}

const style = div.computedStyleMap();
const height = style.get('height');
console.log(height)

Everything above the last 3 lines is the same as before.

Then we call div.computedStyleMap to get a style object that we can use to get the styles.

And then we have:

const height = style.get('height');

to get the CSSheight property value of the div.

This time height should be:

{value: 300, unit: "px"}

The value and unit are separate properties in the returned object.

Conclusion

There’re a few ways we can use to get the CSS properties from an element with JavaScript.

Categories
JavaScript Answers

How to Embed an Auto-Playing YouTube Video in an Iframe with JavaScript?

Sometimes, we may want to embed an auto-playing YouTube video on our web page with JavaScript.

In this article, we’ll look at how to embed an auto-playing YouTube video in an iframe with JavaScript.

Embed Auto-playing YouTub Video

To embed an auto-playing YouTub video, we can write the following code:

<iframe width="420" height="345" src="https://www.youtube.com/embed/n4BSyc7ZLiE?autoplay=1" frameborder="0" allowfullscreen></iframe>

We add an iframe element with the width and height for the video.

In the src attribute, we have the YouTube video embed URL with the autoplay query parameter set to 1 to enable autoplay.

frameborder set to 0 removes the border around the iframe.

allowfullscreen lets us make the iframe full screen.

Conclusion

We can embed an auto-playing video in an iframe by setting the autoplay query parameter of the embed video URL to 1.