Categories
JavaScript Answers

How to add an array of values to a Set with JavaScript?

To add an array of values to a Set with JavaScript, we can call the set add method.

For instance, we write

array.forEach((item) => mySet.add(item));

to call array.forEach with a callback that calls mySet.add to add item in array into the mySet set.

We use forEach to call the same callback for each item in array.

Conclusion

To add an array of values to a Set with JavaScript, we can call the set add method.

Categories
JavaScript Answers

How to preserve line breaks when getting text from a textarea with JavaScript?

To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n'.

For instance, we write

const post = document.createElement("p");
post.textContent = postText;
post.innerHTML = post.innerHTML.replace(/\n/g, "<br>\n");

to call replace to replace all the \n characters with '<br>\n'.

Categories
JavaScript Answers

How to stop an input field in a form from being submitted with HTML?

To stop an input field in a form from being submitted with HTML, we add an input without the name attribute.

For instance, we write

<input type="text" id="in-between" />;

to add a text input without the name attribute.

The field’s value won’t be submitted without the attribute.

Categories
JavaScript Answers

How to use Lodash to sort array of object by value with JavaScript?

To use Lodash to sort array of object by value with JavaScript, we use the orderBy method.

For instance, we write

const sortedChars = _.orderBy(chars, ["name"], ["asc"]);

to call orderBy to sort the chars array by the name property of each object in chars.

We use ['asc'] to specify that we sort by ascending order.

Categories
JavaScript Answers

How to get real mouse position in canvas with JavaScript?

To get real mouse position in canvas with JavaScript, we use the canvas getBoundingClientRect method.

For instance, we write

const getMousePos = (canvas, evt) => {
  const rect = canvas.getBoundingClientRect();
  return {
    x: ((evt.clientX - rect.left) / (rect.right - rect.left)) * canvas.width,
    y: ((evt.clientY - rect.top) / (rect.bottom - rect.top)) * canvas.height,
  };
};

to call canvas.getBoundingClientRect to get an object with the dimensions of the canvas’ bounding rectangle.

Then we get the x and y coordinates of the mouse in the canvas with

((evt.clientX - rect.left) / (rect.right - rect.left)) * canvas.width and ((evt.clientY – rect.top) / (rect.bottom – rect.top)) * canvas.height`.

This takes into account changing coordinates and scaling.