Categories
JavaScript Answers

How to run code after all images have loaded with JavaScript?

Sometimes, we want to run code after all images have loaded with JavaScript.

In this article, we’ll look at how to run code after all images have loaded with JavaScript.

How to run code after all images have loaded with JavaScript?

To run code after all images have loaded with JavaScript, we can create a promise that resolves when all the images are loaded.

For instance, we write:

<img src='https://picsum.photos/200/300'>
<img src='https://picsum.photos/200'>

to add all images.

Then we write:

const imgLoadPromise = img => {
  return new Promise(resolve => {
    img.onload = () => {
      resolve()
    }
  })
}

(async () => {
  const promises = [...document.images]
    .filter(img => !img.complete)
    .map(imgLoadPromise)
  await Promise.all(promises)
  console.log('success')
})()

We create the imgLoadPromise function that takes an img element.

It returns a promise that resolves when img.onload is run. When that’s run, the image is loaded successfully.

Then we create a promise that gets all the images with document.images and spread them into an array.

Next, we call filter with a callback to return with ones that haven’t loaded.

Then we call map with imgLoadPromise to map them to promises.

And then we call Promise.all with promises to wait for all of them to load.

Therefore, when all the images are loaded, 'success' is logged in the console.

Conclusion

To run code after all images have loaded with JavaScript, we can create a promise that resolves when all the images are loaded.

Categories
JavaScript Answers

How to validate currency with JavaScript regex?

Sometimes, we want to validate currency with JavaScript regex.

In this article, we’ll look at how to validate currency with JavaScript regex.

How to validate currency with JavaScript regex?

To validate currency with JavaScript regex, we use the following regex:

/(?=.*?\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|\d+)?(\.\d{1,2})?$/

The (?=.*?\d) part makes sure that the string starts with a number.

^\$?(([1-9]\d{0,2} makes sure the number starts with 1 to 9.

(,\d{3})*) checks that the number has 0 or more groups of 3 digits after the start of the number separated by commas.

We also have \d+ to make the 3 digit groups optional.

Finally, we have ?(\.\d{1,2})?$ to make sure that the number optionally ends with a decimal point and 0 to 2 digits.

Conclusion

To validate currency with JavaScript regex, we use the following regex:

/(?=.*?\d)^\$?(([1-9]\d{0,2}(,\d{3})*)|\d+)?(\.\d{1,2})?$/
Categories
JavaScript Answers

How to convert \n to HTML line breaks?

Sometimes, we want to convert \n to HTML line breaks.

In this article, we’ll look at how to convert \n to HTML line breaks.

How to convert \n to HTML line breaks?

To convert \n to HTML line breaks, we can set the white-space CSS property to pre-line.

For instance, we write:

<span style="white-space: pre-line"></span>

to add a span with the white-space CSS property set to pre-line.

Then we write:

const span = document.querySelector('span')
span.textContent = 'foo \n bar'

We select the span with document.querySelector.

And then we set the textContent of the span to 'foo \n bar' to set that as the content of the span.

Now we should see:

foo
bar

displayed on the screen.

Conclusion

To convert \n to HTML line breaks, we can set the white-space CSS property to pre-line.

Categories
Chart.js JavaScript Answers

How to remove the vertical line in the Chart.js line chart?

Sometimes, we want to remove the vertical line in the Chart.js line chart.

In this article, we’ll look at how to remove the vertical line in the Chart.js line chart.

How to remove the vertical line in the Chart.js line chart?

To remove the vertical line in the Chart.js line chart, we can set the options.scales.x.grid.display property to false.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>

<canvas id='myChart' style='width: 300px; height: 300px'></canvas>

to add the Chart.js script and canvas for the chart.

Then we write:

const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['Monday', 'Tuesday', 'Wednesday'],
    datasets: [{
      label: '# of Votes',
      data: [12, 19, 3],
      borderWidth: 1,
      borderColor: 'green'
    }]
  },
  options: {
    scales: {
      x: {
        grid: {
          display: false
        }
      },
    }
  }
});

to set options.scale.x.grid.display to false to hide the vertical lines in the background.

Now we should only see the horizontal lines displayed in the background.

Conclusion

To remove the vertical line in the Chart.js line chart, we can set the options.scales.x.grid.display property to false.

Categories
Vue Answers

How to add web workers to a Vue app created with Vue-CLI?

Sometimes, we want to add web workers to a Vue app created with Vue-CLI.

In this article, we’ll look at how to add web workers to a Vue app created with Vue-CLI.

How to add web workers to a Vue app created with Vue-CLI?

To add web workers to a Vue app created with Vue-CLI, we can use the worker-plugin package.

To install it, we run:

npm i worker-plugin

Next, ion vue.config.js in the project root, we add:

const WorkerPlugin = require("worker-plugin");

module.exports = {
  configureWebpack: {
    output: {
      globalObject: "this"
    },
    plugins: [new WorkerPlugin()]
  }
};

to load the worker-plugin.

Then we create the workers folder in the src folder with the following 2 files:

worker.js

onmessage = (e) => {
  const {data} = e
  console.log(data);
  postMessage({ foo: "bar" });
};

We call postMessage to send a message to the component that invoked the worker.

index.js

const worker = new Worker("./worker.js", { type: "module" });

const send = (message) =>
  worker.postMessage({
    message
  });

export default {
  worker,
  send
};

Next, we use the worker in a component by writing the following in src/App.vue:

<template>
  <div id="app"></div>
</template>

<script>
import w from "@/workers";

export default {
  name: "App",
  beforeMount() {
    const { worker, send } = w;
    worker.onmessage = (e) => {
      const { data } = e;
      console.log(data);
    };
    send({ foo: "baz" });
  },
};
</script>

We import the workers/index.js with:

import w from "@/workers";

Then we destructure the worker from the imported module with:

const { worker, send } = w;

Then we add a message handler to it with:

worker.onmessage = (e) => {
  const { data } = e;
  console.log(data);
};

And then we send a message to the worker with:

send({ foo: "baz" });

Now we get {foo: 'bar'} from the worker in the worker.onmessage in App.

And in worker.js‘s onmessage function, we get:

{
  message: {
    foo: 'baz'
  }
}

Conclusion

To add web workers to a Vue app created with Vue-CLI, we can use the worker-plugin package.