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 JavaScript ES6 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 Run a Function When a Page has Fully Loaded with JavaScript?

Sometimes, we want to run some code when our web page is fully loaded.

In this article, we’ll look at how to run a function when a page has fully loaded with JavaScript.

Listen to the load Event

The load event is triggered when a page is fully loaded.

Therefore, we can listen to the load event by attaching an event handler function to it to run code when the page is fully loaded.

For instance, we can write:

window.addEventListener('load', () => {  
  console.log("page is loaded")  
})

We call window.addEventListener to listen to the load event triggered on the page.

In the 2nd argument, we pass in a callback function that runs when the load event is triggered.

Therefore, we should see 'page is loaded' logged when the web page is loaded.

Listen to the DOMContentLoaded Event

Likewise, we can listen to the DOMContentLoaded event which is also triggered when the page is fully loaded.

So we can attach an event handler to it the same we did with the load event.

For instance, we can write:

window.addEventListener('DOMContentLoaded', () => {  
  console.log("page is loaded")  
})

to run the callback in the 2nd argument when the page is fully loaded.

Therefore, we should see 'page is loaded' logged when the web page is loaded.

Set the window.onload Method

We can set the window.onload method to a function we want to run code when the page is fully loaded.

This is because window.onload runs when the page is fully loaded.

To do this, we write:

window.onload = () => {  
  console.log("page is loaded")  
}

We just set the onload property to a function we want to run when the page is loaded.

Therefore, we should see 'page is loaded' logged when the web page is loaded.

Conclusion

There are several ways we can use to run a function when a web page fully loaded with JavaScript.

Categories
JavaScript Answers

How to Set a DOM element as the First Child with JavaScript?

Sometimes, we may want to set a DOM element as the first child element with JavaScript.

In this article, we’ll look at ways to set a DOM element as the first child with JavaScript.

Using the prepend Method

In modern browsers, an HTML element object comes with the prepend method to let us prepend an element as the first child.

For instance, if we have the following HTML:

<div>  
  <p>  
    bar  
  </p>  
  <p>  
    baz  
  </p>  
</div>

Then we can write the following JavaScript to prepend an element as the first child of the div:

const div = document.querySelector('div')  
const newChild = document.createElement('p')  
newChild.textContent = 'foo'  
div.prepend(newChild)

We get the div with the document.querySelector method.

Then we call document.createElement to create an element.

Next, we set the textContent property to add some content to the p element we created.

And then we call div.prepend to prepend newChild as the first child of the div.

There’s also the append method to append an element as the last child of a parent element.

Using the insertAdjacentElement Method

We can also use the insertAdjacentElement method to insert an element as the first child of an element.

For instance, if we have the same HTML:

<div>  
  <p>  
    bar  
  </p>  
  <p>  
    baz  
  </p>  
</div>

Then we can write:

const div = document.querySelector('div')  
const newChild = document.createElement('p')  
newChild.textContent = 'foo'  
div.insertAdjacentElement('afterbegin', newChild)

to call insertAdjacentElement with 'afterbegin' and the newChild to prepend newChild as the first child element of the div.

Other possible values for the first argument of insertAdjacentElement is:

  • beforebegin: before the element itself.
  • beforeend: just inside the element, after its last child.
  • afterend: after the element itself.

Using the insertBefore Method

Another method we can use to prepend an element as the first child is to use the insertBefore method.

For instance, we can write:

const div = document.querySelector('div')  
const newChild = document.createElement('p')  
newChild.textContent = 'foo'  
if (div.firstChild) {  
  div.insertBefore(newChild, div.firstChild);  
} else {  
  div.appendChild(childNode);  
}

given the same HTML we have in the previous examples to prepend newChild as the first child of the div.

We check if there’s a firstChild element attached to the div.

If there is, then we call insertBefore to insert newChild before the firstChild of the div.

Otherwise, we just call appendChild to append newChild as a child element.

Conclusion

We can use various HTML element methods to prepend an element as the first child of a parent element.

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.