Categories
JavaScript Answers

How to Detect that an HTML Element’s Dimension has Changed with JavaScript?

Sometimes, we want to detect whether an HTML element’s size has changed.

In this article, we’ll look at how to detect an HTML element that has changed in size.

ResizeObserver

The ResizeObserver API lets us watch for changes in the size of an HTML element.

For instance, we can write:

const div = document.querySelector('div')
const sleep = ms => new Promise((resolve) => setTimeout(resolve, ms));

(async () => {
  for (let i = 0; i < 10; i++) {
    const p = document.createElement('p')
    p.textContent = 'hello'
    div.appendChild(p)
    await sleep(1000)
  }
})();

new ResizeObserver(e => {
  const [{
    borderBoxSize,
    contentBoxSize,
    contentRect,
    devicePixelContentBoxSize: [devicePixelBoxSize]
  }] = e;
  console.log(borderBoxSize, contentBoxSize, contentRect, devicePixelBoxSize)
}).observe(div);

We have a div that we want to watch for size changes.

And we have an async function that adds a p element to the div to change its size every second.

Then we use the ResizeObserver with a callback to watch for size changes.

We call observe to with the div element object to watch for size changes of the div.

In the ResizeObserver callback, we get an event object in the parameter that has info about the element being watched.

We get a few properties in the e object.

The borderBoxSize property lets us get the border-box size of the observed element.

The contentBoxSize property lets us get the content box size of the observed element.

The contentRect property lets us get the new size of the observed element.

The devicePixelContentBoxSize property has the new content-box size in device pixels of the observed element.

These properties are all objects.

borderBoxSize , contentBoxSize , and contentRect properties has the blockSize and inlineSize properties which has the size in pixels depending on whether the element is a block or inline element.

contentRect has the coordinates of the rectangle with the left , right , top and bottom properties.

left and top have the coordinates of the x and y top-left corner in pixels.

right and bottom have the coordinates of the x and y bottom-right corner in pixels.

x and y also have the coordinates of the x and y top-left corner in pixels.

Conclusion

We can use the ResizeObserver API to watch for size changes of a given HTML element.

Categories
JavaScript Answers

How to Replace an Item in a JavaScript Array?

Sometimes, we may want to replace an item in a JavaScript array.

In this article, we’ll look at how to replace an item in a JavaScript array.

Array.prototype.indexOf and Assignment

We can use the JavaScript array’s indexOf method to find the index of a given value in an array.

Then we can use the index to assign the new value to that index.

For instance, we can write:

const arr = [523, 353, 334, 31, 412];
const index = arr.indexOf(353);
if (index !== -1) {
  arr[index] = 1010;
}
console.log(arr)

We call arr.indexOf with the value we’re looking for.

It’ll return the index of the first instance of a value if it exists or -1 otherwise.

So if index isn’t -1, then we can replace the value at the given index with a new one by assigning it as we did in the if block.

So arr is now:

[523, 1010, 334, 31, 412]

Array.prototype.map

We can use the map method to return a new array with the entries of the existing array mapped to new values.

To use this to replace one or more instance of a value, we can write:

const arr = [523, 353, 334, 31, 412];
const mapped = arr.map(a => a == 353 ? 1010 : a)
console.log(mapped)

We call map with a callback that checks if a , which is the value being iterated through is 353.

If it is, then we replace that with 1010.

Otherwise, we just return the existing value.

So mapped is now:

[523, 1010, 334, 31, 412]

Array.prototype.indexOf and Array.prototype.splice

We can also use the JavaScript array’s splice method to replace a value at the given index with a new one.

For instance, we can write:

const arr = [523, 353, 334, 31, 412];
const index = arr.indexOf(353);
if (index !== -1) {
  arr.splice(index, 1, 1010);
}
console.log(arr)

We get the index of 353 the same way.

But instead of assigning the value, we call splice with the index of the element to remove.

1 in the 2nd argument means we remove 1 element.

And the 3rd argument is the value we replace the item with.

So arr is the same as the first example.

Conclusion

We can use array methods to replace an object at the given index with another value.

Categories
JavaScript Answers

How to Get the Index of the Object Inside a JavaScript Array Matching a Given Condition?

Often times in our code, we want to get an object from a JavaScript array that matches the given condition.

In this article, we’ll look at how to find the index of the object that matches the given condition in a JavaScript array.

Array.prototype.findIndex

We can use the JavaScript array’s findIndex method to let us get the index of the object in an array that matches the given condition.

To use it, we write:

const arr = [{
    name: 'james'
  },
  {
    name: 'mary'
  },
  {
    name: 'jane'
  }
];

const index = arr.findIndex(x => x.name === "jane");
console.log(index);

We pass in the findIndex method with a callback that finds the item where the name property’s value is 'jane' .

Therefore, index should be 2.

Lodash findindex Method

If we’re using Lodash in our JavaScript project, we can also use its findIndex method to find the object that matches the given condition in an array.

For instance, we can write:

const arr = [{
    name: 'james'
  },
  {
    name: 'mary'
  },
  {
    name: 'jane'
  }
];

const index = _.findIndex(arr, x => x.name === "jane");
console.log(index);

to pass in the array to the 1st argument and the callback into the 2nd argument.

And we get the same result for index .

We can also pass in an object with the properties to search for.

To do this, we write:

const arr = [{
    name: 'james'
  },
  {
    name: 'mary'
  },
  {
    name: 'jane'
  }
];

const index = _.findIndex(arr, {
  name: 'jane'
});
console.log(index);

And we get the same result.

Array.prototype.map and Array.prototype.indexOf

Another way to find an object in an array that meets the given condition is to map the property values we’re looking for with the map method.

Then we can use indexOf to find the index of the given value assuming the property holds a primitive value.

For instance, we can write:

const arr = [{
    name: 'james'
  },
  {
    name: 'mary'
  },
  {
    name: 'jane'
  }
];

const index = arr.map(a => a.name).indexOf('jane')
console.log(index);

We call map to return an artay with all the name property values from each object.

Then we can call indexOf with what we’re looking for.

And so index should be the same as the other examples.

Conclusion

We can get the index of an object in a JavaScript array that meets the given property value with various array methods.

Categories
JavaScript Answers

How to Get a Character Array From a JavaScript String?

Sometimes, we want to get a character array from a string.

In this article, we’ll look at how to get a character array from a string.

String.prototype.split

A string instance’s split method lets us split a string by any separator.

If we want to get a character array from a string, we can use the split method with an empty string.

For instance, we can write:

const output = "Hello world!".split('');
console.log(output);

Then output is:

["H", "e", "l", "l", "o", " ", "w", "o", "r", "l", "d", "!"]

as a result.

Spread Operator

Another way to split a string into a character array is the spread operator.

We can do this since a string is an iterable object.

To use it, we write:

const output = [..."Hello world!"]
console.log(output);

Then we get the same value for output as before.

RegExp u flag

We can also use the string split method with a regex to split a string into a character array.

For instance, we can write:

const output = "Hello world!".split(/(?=[sS])/u);
console.log(output);

s matches any whitespace and S matches any non-whitespace character.

And the /u flag lets us do searches with Unicode strings properly.

?= is the followed by quantifier.

So we search for anything that follows a whitespace or non-whitespace character and split them.

And so we get the same result as before.

for-of Loop and Array.prototype.push

Since a string is an iterable object, we can for use the for-of loop to loop through each character.

For instance, we can write:

const output = [];
for (const s of "Hello world!") {
  output.push(s);
}
console.log(output);

s has the character from the string.

In the loop body, we call output.push to push character s into the output array.

So we get the same result as before.

Array.from

The Array.from method is a static array method that lets us convert an iterable object into an array.

So we can use it to convert a string into a character array.

For example, we can write:

const output = Array.from("Hello world!")
console.log(output);

And we get the same value for output as before.

Conclusion

There’re many ways to convert a JavaScript string into a character array.

This includes array methods, spread operator, and loops.

Categories
JavaScript Answers

How to Read a Local Text File with JavaScript?

Sometimes, we may want to read a text file stored on a user’s computer with JavaScript.

In this article, we’ll look at how to read a local text file stored on the user’s device with JavaScript.

Get File Content from File Input

We can read file content from a file selected with the file input into our web page.

For instance, we can write the following HTML:

<input type='file' accept='text/plain'>

to add the file input.

Setting accept to text/plain makes the file input only accept plain text files.

And we can add a change event listener to the file input by writing:

const fileInput = document.querySelector('input')
fileInput.addEventListener('change', (event) => {
  const input = event.target;
  const reader = new FileReader();
  reader.onload = () => {
    console.log(reader.result);
  };
  reader.readAsText(input.files[0]);
})

We call addEventListener to 'change' to add a change listener.

Then we get the input with event.target .

And we create a FileReader instance to let us read a file.

We set the onload listener to get the text read from a file with the reader.result property.

Then to read the file, we call reader.readAsText with the first selected file, which is stored in input.files[0] .

Also, we can substitute readAsText with readAsBinaryString to get the same result:

const fileInput = document.querySelector('input')
fileInput.addEventListener('change', (event) => {
  const input = event.target;
  const reader = new FileReader();
  reader.onload = () => {
    console.log(reader.result);
  };
  reader.readAsBinaryString(input.files[0]);
})

Read Text of a Selected File with the text Method

The object with the selected file has the text method to let us read the text from the file object directly.

It returns a promise with the text.

For instance, we can write:

const fileInput = document.querySelector('input')
fileInput.addEventListener('change', async (event) => {
  const text = await event.target.files[0].text()
  console.log(text)
})

to call the text method on the event.target.files[0] file object.

The text variable would then have the text we read from the selected file.

We keep using the file input HTML that we written before.

Conclusion

We can read a file from the FileReader instance or the text method of the selected file object.