Categories
JavaScript Answers

How to add a click event listener on div tag using JavaScript?

Sometimes, we want to add a click event listener on div tag using JavaScript.

In this article, we’ll look at how to add a click event listener on div tag using JavaScript.

How to add a click event listener on div tag using JavaScript?

To add a click event listener on div tag using JavaScript, we can call the addEventListener method on the selected div.

For instance, we write:

<div class='drill_cursor'>
  hello world
</div>

to add a div with a class.

Then we write:

const div = document.querySelector('.drill_cursor');

div.addEventListener('click', (event) => {
  console.log('Hi!');
});

We select the div with document.querySelector.

Then we call addEventListener with 'click' to add a click event listener.

And then we set the click event listener to a function that logs 'Hi!' in the console.

Therefore, when we click on the div, we should see 'Hi!' logged.

Conclusion

To add a click event listener on div tag using JavaScript, we can call the addEventListener method on the selected div.

Categories
JavaScript Answers

How to get the response JSON and response status with JavaScript fetch?

Sometimes, we want to get the response JSON and response status with JavaScript fetch.

In this article, we’ll look at how to get the response JSON and response status with JavaScript fetch.

How to get the response JSON and response status with JavaScript fetch?

To get the response JSON and response status with JavaScript fetch, we can get the status property from the response object.

For instance, we write:

(async () => {
  const r = await fetch("https://jsonplaceholder.typicode.com/posts/1")
  const body = await r.json()
  const {
    status
  } = r
  const obj = {
    status,
    body
  }
  console.log(obj)
})()

We make a GET request with fetch.

Then we call r.json to get the response body JSON.

Next, we get the status property from the r response object.

And then we combine them into one object and assign it to obj.

Therefore, obj is:

{
  "status": 200,
  "body": {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  }
}

Conclusion

To get the response JSON and response status with JavaScript fetch, we can get the status property from the response object.

Categories
JavaScript Answers

How to auto-highlight an input field on focus with JavaScript?

Sometimes, we want to auto-highlight an input field on focus with JavaScript.

In this article, we’ll look at how to auto-highlight an input field on focus with JavaScript.

How to auto-highlight an input field on focus with JavaScript?

To auto-highlight an input field on focus with JavaScript, we can call select on the element when the focus event is emitted.

For instance, we write:

<input type="text" value="test" />

to add an input with a value filled in.

Then we write:

const input = document.querySelector('input')

input.addEventListener('focus', () => {
  input.select()
})

to select the input with document.querySelector.

And then we call input.addEventListener to add a focus event listener.

In the event handler, we call input.select to highlight the value in the input box.

As a result, we see the input box value highlighted when we click inside the input box.

Conclusion

To auto-highlight an input field on focus with JavaScript, we can call select on the element when the focus event is emitted.

Categories
JavaScript Answers

How to select Fabric.js object programmatically with JavaScript?

Sometimes, we want to select Fabric.js object programmatically with JavaScript.

In this article, we’ll look at how to select Fabric.js object programmatically with JavaScript.

How to select Fabric.js object programmatically with JavaScript?

To select Fabric.js object programmatically with JavaScript, we can use the canvas.setActiveObject method.

For instance, we write:

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/460/fabric.min.js"></script>

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

We add the fabric.js script and the canvas element.

Then we write:

const canvas = new fabric.Canvas('canvas');

canvas.add(new fabric.Rect({
  left: 80,
  top: 80,
  width: 75,
  height: 50,
  fill: 'green',
  stroke: 'black',
  strokeWidth: 3,
  padding: 10
}));

canvas.add(new fabric.Circle({
  left: 50,
  top: 50,
  radius: 30,
  fill: 'gray',
  stroke: 'black',
  strokeWidth: 3
}));

canvas.setActiveObject(canvas.item(0));

We use the fabric.Canvas constructor with the ID of the canvas to create a fabric canvas.

Then we call canvas.add to add a rectangle and circle at various positions, shapes, fill and sizes.

Then we set the select item to the item we added first, which is the rectangle, by writing:

canvas.setActiveObject(canvas.item(0));

We call canvas.setActiveObject with canvas.item(0) to select the first object to be selected,.

Conclusion

To select Fabric.js object programmatically with JavaScript, we can use the canvas.setActiveObject method.

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.